`
sulifeng
  • 浏览: 40072 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
卡片式布局 android
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
		<shape android:shape="rectangle"
			android:dither="true">
 
			<corners android:radius="2dp"/>
 
			<solid android:color="#ccc" />
 
		</shape>
	</item>
 
	<item android:bottom="2dp">
		<shape android:shape="rectangle"
			android:dither="true">
 
			<corners android:radius="2dp" />
 
			<solid android:color="@android:color/white" />
 
			<padding android:bottom="8dp"
				android:left="8dp"
				android:right="8dp"
				android:top="8dp" />
		</shape>
	</item>
</layer-list>
模拟ProgressDialog--利用ClipDrawable
ImageView imageView = (ImageView) findViewById(id.iv_progress);
ClipDrawable mClipDrawable = (ClipDrawable) imageView.getDrawable();
mClipDrawable.setLevel(x);//x+100




<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/iv_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/loading_bg"
    android:paddingLeft="3dp"
    android:paddingTop="3dp"
    android:scaleType="centerInside"
    android:src="@drawable/clip_loading" />

loading_bg.png是固定的背景,比如说黑色的方形图片,中间一个白色的心形
clip_loading.xml:

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="vertical"
    android:drawable="@drawable/loading_progress"
    android:gravity="bottom" >

</clip>


loading_progress.png是一个红色的心形图片

ClipDrawable能从一个张图片中剪出一部分作为显示(可以通过setLevel设置剪的幅度),这样就能实现从底部往上,心形从全白变成全红的效果.



ProgressBar-旋转单张图片+固定背景图
  <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminateDrawable="@drawable/rotate_loading_github"
            android:indeterminateDuration="1800" />




<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/github_loading_inner"/>
    <item>
        <rotate
            android:fromDegrees="0"
            android:interpolator="@android:anim/linear_interpolator"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="360" >
            <bitmap
                android:antialias="true"
                android:filter="true"
                android:src="@drawable/github_loading_outer" />
        </rotate>
    </item>

</layer-list>
ProgressBar-旋转单张图片
 <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminateDrawable="@drawable/rotate_loading_360"
            android:indeterminateDuration="1800" />



<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" >

    <bitmap
        android:antialias="true"
        android:filter="true"
        android:src="@drawable/loading_360" />

</rotate>
arraylist去重,保留原有顺序
ArrayList<Person> newlist = new ArrayList<Person>(
				new LinkedHashSet<Person>(list));
java基础
1.删除ArrayList中的指定重复元素:
   list.removeAll(Collections.singleton(new Person("tom",1)));
JNI基础 https://svn.apache.org/repos/asf/harmony/enhanced/buildtest/trunk/tests/vts/vm/src/test/vm/jni/static_methods/CallStaticCharMethodVTest/CallStaticCharMethodVTest.c
CallStaticObjectMethodA的用法:

jvalue在jni.h中被定义成如下联合体
struts union jvalue{
        jboolean z;
        jbyte  b;
        jchar  c;
        jshort  s;
        jint  i;
        jlong j;
        jfloat f;
        jdouble d;
        jobject l;
} jvalue;




IMPLEMENT_GetStaticMethodID_METHOD("Test1", "Test1_method_string_static", "(ZBCSIJFDLjava/lang/String;[Ljava/lang/String;)Ljava/lang/String;");
  char *path = "asdf";
  jstring jpath=env->NewStringUTF("sdsadasdasd");
  jvalue *args  = new jvalue[10];
  args[0].z = JNI_FALSE;
  args[1].b = MIN_JBYTE;
  args[2].c = 'a';
  args[3].s = MAX_JSHORT;
  args[4].i = 123;
  args[5].j = 0;
  args[6].f = 0;
  args[7].d = 100;
  args[8].l = NULL;
  args[9].l = NULL;
  jstring value = (jstring)env->CallStaticObjectMethodA(clazz, MethodID, args);




/*** java层Test1_method_string_static函数的实现:**/

 public static String Test1_method_string_static(boolean bb, byte by, char ch, short sh, int in, long lg, float fl, double db, String str, String strarr[]){
      System.out.println("Test1_method_string_static passed!");
      return str;
  }

==============================================================

CallStaticCharMethodV的用法:
static jchar callNI(JNIEnv *env, jclass par_cl, jmethodID mid, ...)
{
    va_list args;
        jchar result;

        va_start(args, mid);
        result = (*env)->CallStaticCharMethodV(env, par_cl, mid, args);
        va_end(args);
        return result;
}
用layer-list给按钮增加阴影 android http://stackoverflow.com/questions/15333529/how-to-provide-shadow-to-button
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item><layer-list>
                <item android:right="5dp" android:top="5dp"><shape>
                        <corners android:radius="3dp" />

                        <solid android:color="#D6D6D6" />
                    </shape></item>
                <item android:bottom="2dp" android:left="2dp"><shape>
                        <gradient android:angle="270" android:endColor="#E2E2E2" android:startColor="#BABABA" />

                        <stroke android:width="1dp" android:color="#BABABA" />

                        <corners android:radius="4dp" />

                        <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
                    </shape></item>
            </layer-list></item>
</selector>




/**********************************************/

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list xmlns:android="http://schemas.android.com/apk/res/android">

            <!-- Bottom Shadow -->
            <item android:left="2.0dp" android:right="2.0dp"><shape android:shape="rectangle">
                    <corners android:radius="12dp" />

                    <padding android:bottom="4dp" android:left="0dp" android:right="0dp" android:top="0dp" />
                    <gradient android:angle="270" android:centerColor="#FF222222" android:centerX="0.15" android:endColor="#44DDDDDD" android:startColor="#FF000000"></gradient>
                </shape></item>

            <!-- White Top color -->
            <item><shape android:shape="rectangle">
                    <solid android:color="#28517b" />

                    <corners android:radius="12dp" />
                </shape></item>
        </layer-list></item>

</selector>

/***********************************************/


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="false">
        <layer-list>
            <item><shape>
                    <corners android:radius="15dp" />

                    <solid android:color="#1F71A3" />
                </shape></item>
            <item android:bottom="6dp"><shape>
                    <gradient android:angle="270" 
                        android:centerColor="#4C9DCE" 
                        android:endColor="#59AAD5" 
                        android:startColor="#3595C7" />

                    <corners android:radius="10dp" />
                </shape></item>
        </layer-list></item>

 <item android:state_pressed="true">
        <layer-list>
            <item><shape>
                    <corners android:radius="15dp" />

                    <solid android:color="#1F71A3" />
                </shape></item>
            <item android:bottom="0dp"><shape>
                    <gradient android:angle="270" 
                        android:centerColor="#4C9DCE" 
                        android:endColor="#59AAD5" 
                        android:startColor="#3595C7" />

                    <corners android:radius="10dp" />
                </shape></item>
        </layer-list></item>

</selector>
android log
打印调用者的信息:
protected static String buildMessage(String msg) {      
        StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2];

         return new StringBuilder()
                .append(caller.getClassName())
                .append(".")
                .append(caller.getMethodName())
                .append("(): ")
                .append(msg).toString();
    }
   public static void i(String msg) {
        android.util.Log.i(TAG, buildMessage(msg));
    }
    
  
  
  
   例如你在一个函数里打了log,结果却输出了若干条log,只有一条是你想要的,由于调用者也有若干个,你不知道这一条是被谁调用而产生的,这时候只需把所有的调用都打印出来即可.
  例如:
  String result ="";
  StackTraceElement[] traces=new Throwable().fillInStackTrace().getStackTrace();
  int count=6;
  int j=traces.length>=count? count:traces.length;
  for (int i = 0; i < j; i++) {
	 String classname= traces[i].getClassName();
	 result=result +"  ->  " +classname.substring(classname.lastIndexOf(".")+1)+"."+traces[i].getMethodName();
				
  }
test
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
    <item android:state_focused="true" android:state_enabled="true" android:color="@android:color/black"/>
    <item android:state_selected="true" android:state_enabled="true" android:color="@android:color/black"/>
    <item android:state_focused="true" android:state_pressed="true"  android:state_enabled="true" android:color="@android:color/black"/>
    <item android:state_enabled="true" android:color="@android:color/white"/>
    <item android:state_enabled="false" android:color="#40000000"/>
    <item android:state_focused="true" android:state_enabled="false" android:color="#40000000"/>
    <item android:state_selected="true" android:state_enabled="false" android:color="#40000000"/>
    <item android:state_focused="true" android:state_pressed="true"  android:state_enabled="false" android:color="#40000000"/>
</selector>
listview局部刷新
	public void setFavoriteShow(int position) {

		
		

		int visiblePosition = songsView.listview.getFirstVisiblePosition();
		// 只有当要更新的view在可见的位置时才更新,不可见时,跳过不更新
		if (position - visiblePosition >= 0) {
			// 得到要更新的item的view
			View view = songsView.listview.getChildAt(position
					- visiblePosition);
			View isFavorite =view.findViewById(R.id.isFavorite);
			isFavorite.setVisibility(View.VISIBLE);

		}

	}
对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("注意");
                
                LayoutInflater inflater = LayoutInflater.from(this);
                final View view = inflater.inflate(R.layout.main, null);
                builder.setView(view);
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int idx) {
                                EditText et = (EditText) view.findViewById(R.id.editText);
                                Log.d("Sample", et.getText().toString());
                        }
                });

                builder.show();
走马灯的TextView
 

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;

/**
 * 自定义TextView
 * 
 * 
 */
public class MyMarqueeTextView extends TextView implements Runnable {
	private MarqueeText marqueeText;
	String TAG = "MyMarqueeTextView";

	public MyMarqueeTextView(Context context, AttributeSet attrs) {
		super(context, attrs);

		marqueeText = new MarqueeText(this.getText().toString());

		marqueeText.setTextSize(this.getTextSize());

		marqueeText.setTextColor(this.getCurrentTextColor());// 从xml里拿出颜色

		marqueeText.setGravity(this.getGravity());

		new Thread(this).start();
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {

		marqueeText.setViewWidth(getWidth());// xml里一般是写死了宽度的
		marqueeText.setViewHeight(getHeight());

		super.onLayout(changed, left, top, right, bottom);
	}

	/**
	 * 设置要滚动的内容
	 * 
	 * @param textcontet
	 */
	public void setText(String textcontet) {

		marqueeText.setText(textcontet);

	}

	/**
	 * 是否在过短时停止走马灯效果
	 * 
	 * @param isStopWhenNotLongEnough
	 */
	public void setStopWhenNotLongEnough(boolean isStopWhenNotLongEnough) {

		marqueeText.setStopWhenNotLongEnough(isStopWhenNotLongEnough);
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 1.刷新
				postInvalidate();
				// 2.睡眠
				Thread.sleep(200L);
				// 3.移?				marqueeText.move();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {

		// 绘制文字
		marqueeText.draw(canvas);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(measureWidth(widthMeasureSpec),
				measureHeight(heightMeasureSpec));
	}

	private int measureWidth(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		if (specMode == MeasureSpec.EXACTLY) {
			// We were told how big to be
			result = specSize;
		} else {
			// Measure the text
			result = (int) marqueeText.paint.measureText(marqueeText.content)
					+ getPaddingLeft() + getPaddingRight();
			if (specMode == MeasureSpec.AT_MOST) {
				// Respect AT_MOST value if that was what is called for by
				// measureSpec
				result = Math.min(result, specSize);
			}
		}
		Log.i(TAG, "measureWidth   = " + result);
		return result;
	}

	/**
	 * Determines the height of this view
	 * 
	 * @param measureSpec
	 *            A measureSpec packed into an int
	 * @return The height of the view, honoring constraints from measureSpec
	 */
	private int measureHeight(int measureSpec) {
		int result = 0;
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);

		int ascent = (int) marqueeText.paint.ascent();
		if (specMode == MeasureSpec.EXACTLY) {
			// We were told how big to be
			result = specSize;
		} else {
			// Measure the text (beware: ascent is a negative number)
			// result = (int) (-ascent + marqueeText.paint.descent()) +
			// getPaddingTop()
			// + getPaddingBottom();
			result = (int) Math
					.ceil((marqueeText.fontMetrics.bottom - marqueeText.fontMetrics.top));
			if (specMode == MeasureSpec.AT_MOST) {
				// Respect AT_MOST value if that was what is called for by
				// measureSpec
				result = Math.min(result, specSize);
			}
		}
		return result;
	}

	class MarqueeText {
		public Paint paint;
		private String content;// 文字内容

		float ax = 0; // 循环画2个文本,第一个文本的x
		float bx = 0;// 第二个文本的x
		float y = 0;
		int space = 70; // 循环显示文字,space表示循环的空白间隔 ,例如 (cdefg ab)中的空白

		int stepX = 5;// 移动步长
		private float textWidth;// 文字宽度

		int viewWidth; // 控件的宽度
		int viewHeight;// 控件的高度
		int textColor = Color.BLACK;
		float textSize = 22;// 默认字体大小是22

		boolean stopWhenNotLong = true;

		int gravity = Gravity.LEFT;
		FontMetrics fontMetrics = null;

		public MarqueeText(String content) {

			paint = new Paint();
			paint.setAntiAlias(true);
			setText(content);

			setTextColor(textColor);

			setTextSize(textSize);

			setViewWidth(0);

		}

		public void setGravity(int gravity) {
			this.gravity = gravity;

		}

		public void setViewHeight(int height) {
			this.viewHeight = height;
			computeY();
		}

		public void setStopWhenNotLongEnough(boolean isStopWhenNotLongEnough) {
			this.stopWhenNotLong = isStopWhenNotLongEnough;
		}

		/**
		 * 
		 * @param content
		 */
		public void setText(String content) {
			this.content = content;
			fontMetrics = paint.getFontMetrics();
			computeY();
		}

		public void setViewWidth(int edgewidth) {
			this.viewWidth = edgewidth;
			space = viewWidth / 2;
			computeY();
		}

		public void setTextColor(int color) {
			this.textColor = color;
			paint.setColor(textColor);

		}

		public void setTextSize(float textsize) {
			this.textSize = textsize;
			paint.setTextSize(textsize);

			fontMetrics = paint.getFontMetrics();
			computeY();

		}

		public void computeY() {
			Rect bounds = new Rect();
			paint.getTextBounds(content, 0, content.length(), bounds);
			Log.i(TAG,
					"bounds=  width:" + bounds.width() + " height:"
							+ bounds.height() + ", content=" + content
							+ ",viewwidth=" + viewWidth + ",textwidth="
							+ textWidth);
			textWidth = bounds.width();

//			y = Math.abs(fontMetrics.ascent) - 1;
			y = Math.abs(fontMetrics.top);
		}

		public void move() {

			if (ax <= bx) {

				ax -= stepX;
				bx = textWidth + ax + space;

				if (ax <= -textWidth) {

					ax = bx + (int) textWidth + space;
				}

			} else {
				bx -= stepX;

				ax = (int) textWidth + bx + space;

				if (bx <= -textWidth) {
					bx = ax + textWidth + space;
				}
			}

		}

		public void draw(Canvas canvas) {

			if (textWidth >= viewWidth || !stopWhenNotLong) {
				canvas.drawText(content, ax, y, paint);
				canvas.drawText(content, bx, y, paint);
			} else {

				if (gravity == Gravity.LEFT) {
					canvas.drawText(content, 0, y, paint);
				} else if (gravity == Gravity.RIGHT) {
					canvas.drawText(content, viewWidth - textWidth, y, paint);
				} else if (gravity == Gravity.CENTER) {

					canvas.drawText(content, (viewWidth - textWidth) / 2, y,
							paint);// 居中,只画一遍

				} else {
					canvas.drawText(content, 0, y, paint);
				}

			}

		}
	}
}
Android Selector的常用写法(按钮)
button_selector.xml:



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape>
            <solid android:color="#993434" />

            <stroke android:width="1dp" android:color="#171717" />

            <corners android:radius="3dp" />

            <padding android:bottom="10dp" android:left="30dp" android:right="30dp" android:top="10dp" />
        </shape></item>
    <item><shape>
            <gradient android:angle="270" android:endColor="#171717" android:startColor="#343434" />

            <stroke android:width="1dp" android:color="#171717" />

            <corners android:radius="3dp" />

            <padding android:bottom="10dp" android:left="30dp" android:right="30dp" android:top="10dp" />
        </shape></item>

</selector>





styles.xml:




<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
    </style>
    <style name="AppTheme" parent="AppBaseTheme">
    </style>
 
    <style name="ButtonText"> 
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#ffffff</item>
        <item name="android:gravity">center</item>
        <item name="android:textStyle">bold</item>
        <item name="android:shadowColor">#000000</item>
        <item name="android:shadowDx">1</item>
        <item name="android:shadowDy">1</item>
        <item name="android:shadowRadius">2</item>
        <item name="android:background">@drawable/customer_button_selector</item>
    </style>

</resources>

如何编写一个类似AirDroid(在PC上管理手机资源)的应用 http://www.jdepths.com/2012/12/how-to-create-android-app-like-airdroid.html
由代码可知使用了jetty作为服务器,例子里用的是servlet.如何支持JSP?
1.有个专门的jetty for android: https://code.google.com/p/i-jetty/,但似乎对jsp支持得不好(或者说不支持)
2.反编译了AirDroid后,发现assets文件夹下有html,js,css,swf等文件.似乎没有php或jsp等动态语言的痕迹
httpclient4.2.2的几个常用方法,登录之后访问页面问题,下载文件 java
1.基本的get
 
Java代码  
public void getUrl(String url, String encoding)  
            throws ClientProtocolException, IOException {  
        // 默认的client类。  
        HttpClient client = new DefaultHttpClient();  
        // 设置为get取连接的方式.  
        HttpGet get = new HttpGet(url);  
        // 得到返回的response.  
        HttpResponse response = client.execute(get);  
        // 得到返回的client里面的实体对象信息.  
        HttpEntity entity = response.getEntity();  
        if (entity != null) {  
            System.out.println("内容编码是:" + entity.getContentEncoding());  
            System.out.println("内容类型是:" + entity.getContentType());  
            // 得到返回的主体内容.  
            InputStream instream = entity.getContent();  
            try {  
                BufferedReader reader = new BufferedReader(  
                        new InputStreamReader(instream, encoding));  
                System.out.println(reader.readLine());  
            } catch (Exception e) {  
                e.printStackTrace();  
            } finally {  
                instream.close();  
            }  
        }  
  
        // 关闭连接.  
        client.getConnectionManager().shutdown();  
    }  
 
2.基本的Post
   下面的params参数,是在表单里面提交的参数。
 
Java代码  
public void postUrlWithParams(String url, Map params, String encoding)  
            throws Exception {  
        DefaultHttpClient httpclient = new DefaultHttpClient();  
        try {  
  
            HttpPost httpost = new HttpPost(url);  
            // 添加参数  
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
            if (params != null && params.keySet().size() > 0) {  
                Iterator iterator = params.entrySet().iterator();  
                while (iterator.hasNext()) {  
                    Map.Entry entry = (Entry) iterator.next();  
                    nvps.add(new BasicNameValuePair((String) entry.getKey(),  
                            (String) entry.getValue()));  
                }  
            }  
  
            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  
  
            HttpResponse response = httpclient.execute(httpost);  
            HttpEntity entity = response.getEntity();  
  
            System.out.println("Login form get: " + response.getStatusLine()  
                    + entity.getContent());  
            dump(entity, encoding);  
            System.out.println("Post logon cookies:");  
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();  
            if (cookies.isEmpty()) {  
                System.out.println("None");  
            } else {  
                for (int i = 0; i < cookies.size(); i++) {  
                    System.out.println("- " + cookies.get(i).toString());  
                }  
            }  
  
        } finally {  
            // 关闭请求  
            httpclient.getConnectionManager().shutdown();  
        }  
    }  
 
3。打印页面输出的小代码片段
 
Java代码  
private static void dump(HttpEntity entity, String encoding)  
            throws IOException {  
        BufferedReader br = new BufferedReader(new InputStreamReader(  
                entity.getContent(), encoding));  
        System.out.println(br.readLine());  
    }  
 
4.常见的登录session问题,需求:使用账户,密码登录系统之后,然后再访问页面不出错。
 
	特别注意,下面的httpclient对象要使用一个,而不要在第二次访问的时候,重新new一个。至于如何保存这个第一步经过了验证的httpclient,有很多种方法实现。单例,系统全局变量(android 下面的Application),ThreadLocal变量等等。
 
       以及下面创建的httpClient要使用ThreadSafeClientConnManager对象!
 
   public String getSessionId(String url, Map params, String encoding,
Java代码  
        String url2) throws Exception {  
    DefaultHttpClient httpclient = new DefaultHttpClient(  
            new ThreadSafeClientConnManager());  
    try {  
  
        HttpPost httpost = new HttpPost(url);  
        // 添加参数  
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        if (params != null && params.keySet().size() > 0) {  
            Iterator iterator = params.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Map.Entry entry = (Entry) iterator.next();  
                nvps.add(new BasicNameValuePair((String) entry.getKey(),  
                        (String) entry.getValue()));  
            }  
        }  
        // 设置请求的编码格式  
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  
        // 登录一遍  
        httpclient.execute(httpost);  
        // 然后再第二次请求普通的url即可。  
        httpost = new HttpPost(url2);  
        BasicResponseHandler responseHandler = new BasicResponseHandler();  
        System.out.println(httpclient.execute(httpost, responseHandler));  
    } finally {  
        // 关闭请求  
        httpclient.getConnectionManager().shutdown();  
    }  
    return "";  
}  
 
5.下载文件,例如mp3等等。
 
Java代码  
//第一个参数,网络连接;第二个参数,保存到本地文件的地址  
public void getFile(String url, String fileName) {  
        HttpClient httpClient = new DefaultHttpClient();  
        HttpGet get = new HttpGet(url);  
        try {  
            ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {  
                public byte[] handleResponse(HttpResponse response)  
                        throws ClientProtocolException, IOException {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                        return EntityUtils.toByteArray(entity);  
                    } else {  
                        return null;  
                    }  
                }  
            };  
  
            byte[] charts = httpClient.execute(get, handler);  
            FileOutputStream out = new FileOutputStream(fileName);  
            out.write(charts);  
            out.close();  
  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            httpClient.getConnectionManager().shutdown();  
        }  
    }  
 
6.创建一个多线程环境下面可用的httpClient
(原文:http://blog.csdn.net/jiaoshi0531/article/details/6459468)
 
Java代码  
              HttpParams params = new BasicHttpParams();  
//设置允许链接的做多链接数目  
ConnManagerParams.setMaxTotalConnections(params, 200);  
//设置超时时间.  
ConnManagerParams.setTimeout(params, 10000);  
//设置每个路由的最多链接数量是20  
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);  
//设置到指定主机的路由的最多数量是50  
HttpHost localhost = new HttpHost("127.0.0.1",80);  
connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50);  
ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);  
//设置链接使用的版本  
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
//设置链接使用的内容的编码  
HttpProtocolParams.setContentCharset(params,  
        HTTP.DEFAULT_CONTENT_CHARSET);  
//是否希望可以继续使用.  
HttpProtocolParams.setUseExpectContinue(params, true);  
  
SchemeRegistry schemeRegistry = new SchemeRegistry();  
schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));  
schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));  
ClientConnectionManager cm = new ThreadSafeClientConnManager(params,schemeRegistry);  
httpClient = new DefaultHttpClient(cm, params);   
 
7.实用的一个对象,http上下文,可以从这个对象里面取到一次请求相关的信息,例如request,response,代理主机等。
 
Java代码  
public static void getUrl(String url, String encoding)  
            throws ClientProtocolException, IOException {  
        // 设置为get取连接的方式.  
        HttpGet get = new HttpGet(url);  
        HttpContext localContext = new BasicHttpContext();  
        // 得到返回的response.第二个参数,是上下文,很好的一个参数!  
        httpclient.execute(get, localContext);  
  
        // 从上下文中得到HttpConnection对象  
        HttpConnection con = (HttpConnection) localContext  
                .getAttribute(ExecutionContext.HTTP_CONNECTION);  
        System.out.println("socket超时时间:" + con.getSocketTimeout());  
  
        // 从上下文中得到HttpHost对象  
        HttpHost target = (HttpHost) localContext  
                .getAttribute(ExecutionContext.HTTP_TARGET_HOST);  
        System.out.println("最终请求的目标:" + target.getHostName() + ":"  
                + target.getPort());  
  
        // 从上下文中得到代理相关信息.  
        HttpHost proxy = (HttpHost) localContext  
                .getAttribute(ExecutionContext.HTTP_PROXY_HOST);  
        if (proxy != null)  
            System.out.println("代理主机的目标:" + proxy.getHostName() + ":"  
                    + proxy.getPort());  
  
        System.out.println("是否发送完毕:"  
                + localContext.getAttribute(ExecutionContext.HTTP_REQ_SENT));  
  
        // 从上下文中得到HttpRequest对象  
        HttpRequest request = (HttpRequest) localContext  
                .getAttribute(ExecutionContext.HTTP_REQUEST);  
        System.out.println("请求的版本:" + request.getProtocolVersion());  
        Header[] headers = request.getAllHeaders();  
        System.out.println("请求的头信息: ");  
        for (Header h : headers) {  
            System.out.println(h.getName() + "--" + h.getValue());  
        }  
        System.out.println("请求的链接:" + request.getRequestLine().getUri());  
  
        // 从上下文中得到HttpResponse对象  
        HttpResponse response = (HttpResponse) localContext  
                .getAttribute(ExecutionContext.HTTP_RESPONSE);  
        HttpEntity entity = response.getEntity();  
        if (entity != null) {  
            System.out.println("返回结果内容编码是:" + entity.getContentEncoding());  
            System.out.println("返回结果内容类型是:" + entity.getContentType());  
            dump(entity, encoding);  
        }  
    }  
 输出结果大致如下:
 
Txt代码  
socket超时时间:0  
最终请求的目标:money.finance.sina.com.cn:-1  
是否发送完毕:true  
请求的版本:HTTP/1.1  
请求的头信息:   
Host--money.finance.sina.com.cn  
Connection--Keep-Alive  
User-Agent--Apache-HttpClient/4.2.2 (java 1.5)  
请求的链接:/corp/go.php/vFD_BalanceSheet/stockid/600031/ctrl/part/displaytype/4.phtml  
返回结果内容编码是:null  
返回结果内容类型是:Content-Type: text/html  
 
8.设置代理
 
Java代码  
             //String  hostIp代理主机ip,int port  代理端口  
tpHost proxy = new HttpHost(hostIp, port);  
// 设置代理主机.  
tpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
proxy);  
 
9.设置保持链接时间
Java代码  
//在服务端设置一个保持持久连接的特性.  
        //HTTP服务器配置了会取消在一定时间内没有活动的链接,以节省系统的持久性链接资源.  
        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {  
            public long getKeepAliveDuration(HttpResponse response,  
                    HttpContext context) {  
                HeaderElementIterator it = new BasicHeaderElementIterator(  
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));  
                while (it.hasNext()) {  
                    HeaderElement he = it.nextElement();  
                    String param = he.getName();  
                    String value = he.getValue();  
                    if (value != null && param.equalsIgnoreCase("timeout")) {  
                        try {  
                            return Long.parseLong(value) * 1000;  
                        } catch (Exception e) {  
  
                        }  
                    }  
                }  
                HttpHost target = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);  
                if("www.baidu.com".equalsIgnoreCase(target.getHostName())){  
                    return 5*1000;  
                }  
                else  
                    return 30*1000;   
            }   
        });  
FileChannel复制文件 java基础 http://crunchify.com/java-tips-what-is-the-fastest-way-to-copy-file-in-java/
package com.crunchify.tutorials;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
 
/**
 * @author Crunchify.co
 */
 
public class CrunchifyFileCopy {
 
    public static void main(String[] args) {
        File file1 =new File("/Users/<username>/Documents/file1.txt");
        File file2 =new File("/Users/<username>/Documents/file2.txt");
        try {
            fileCopy(file1, file2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    // Fastest way to Copy file in Java
    @SuppressWarnings("resource")
    public static void fileCopy( File in, File out ) throws IOException
    {
        FileChannel inChannel = new FileInputStream( in ).getChannel();
        FileChannel outChannel = new FileOutputStream( out ).getChannel();
        try
        {
            // Try to change this but this is the number I tried.. for Windows, 64Mb - 32Kb)
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while ( position < size )
            {
               position += inChannel.transferTo( position, maxCount, outChannel );
            }
            System.out.println("File Successfully Copied..");
        }
        finally
        {
            if ( inChannel != null )
            {
               inChannel.close();
            }
            if ( outChannel != null )
            {
                outChannel.close();
            }
        }
    }
}
从url中读取出parameter java
public static String GetParameter(String url, String target) {
		String param = url.substring(url.indexOf("?") + 1);
		Map<String, List<String>> getRequestParams = new HashMap<String, List<String>>();
		String[] params = param.split("&");
		int index = 0;
		String key = null;
		String value = null;
		for (int i = 0; i < params.length; i++) {

			index = params[i].indexOf("=");
			if (index > -1) {
				try {
					key = params[i].substring(0, index);
					key = URLDecoder.decode(key, "ISO8859-1");
					value = params[i].substring(index + 1);
					value = URLDecoder.decode(value, "ISO8859-1");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				List<String> values = getRequestParams.get(key);
				if (values == null) {
					values = new ArrayList<String>();
					getRequestParams.put(key, values);
				}
				values.add(value);
			}

		}

		List<String>result= getRequestParams.get(target);
		if (result!=null&& result.size()>0) {
			return result.get(0);
		}
		return null;
	}
Android源码中的单例
public class BluetoothOppManager {
    private static BluetoothOppManager INSTANCE;
    
    private static Object INSTANCE_LOCK = new Object();
/** 
    * Get singleton instance. 
    */ 
   public static BluetoothOppManager getInstance(Context context) { 
       synchronized (INSTANCE_LOCK) { 
           if (INSTANCE == null) { 
               INSTANCE = new BluetoothOppManager(); 
           } 
           INSTANCE.init(context);
           return INSTANCE; 
       } 
   }
}
用反射判断api类是否存在
try {
			Class className = Class.forName("Function");
			Object object = className.newInstance();

			Method method1 = className.getMethod("setByte", byte[].class);
			
			Constructor constructor =className.getConstructor(String.class);
			Object obj= constructor.newInstance("args");

			byte timeStyle[] = new byte[1];

			method1.invoke(object, timeStyle);

			System.out.println(timeStyle[0]);

		} catch (Exception e) {

			e.printStackTrace();
			
		}
LruCache的使用 android
final int memClass = ((ActivityManager)context  
                    .getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();  
  
            // Use 1/8th of the available memory for this memory cache.  
         int   mCacheSize = 1024 * 1024 * memClass / 8;  
          LruCache  mLruCache = new LruCache<String, Bitmap>(mCacheSize) {  
                @Override  
                protected int sizeOf(String key, Bitmap bitmap) {  
                    // The cache size will be measured in bytes rather than  
                    // number of items.  
                    return bitmap.getRowBytes() * bitmap.getHeight();  
                }  
  
                @Override  
                protected void entryRemoved(boolean evicted, String key, Bitmap oldValue,  
                        Bitmap newValue) {  
                    if (evicted && oldValue !=null && !oldValue.isRecycled()) {  
                        oldValue.recycle();  
                        oldValue = null;  
                    }  
                }  
            };  

//////////////////////////////////////////////////////////////////////////////////
  //在OnDestroy里调用,回收整个LruCache
public static void recycle() {  
       
        if (mLruCache != null) {  
            mLruCache.evictAll();  
            mLruCache = null;  
        }  
        
    }  
C++调用sqlite c/c++
sqlite3 *db=NULL;//声明sqlite关键结构指针
	
	int ret = -1;
	int row=0,column=0;//用于记录下面结果集中的行数和列数
	char *zErrMsg = 0;
	char **result;//二维数组用于存放结果

		
	char *sql="select * from xxxtable";//查询的sql语句
	  
	  
	
	int rc= sqlite3_open("xxx.db", &db); //打开指定文件
	
	
	if(rc!=SQLITE_OK){//或者直接是rc ,各种返回码的意义:http://o0o0o0o.iteye.com/blog/1243468
		LOGI("Error---->Can't open database");
		sqlite3_close(db);
		//return NPT_FAILURE;
	}
	
	ret=sqlite3_get_table(db,sql,&result,&row,&column,&zErrMsg);//result:以数组的形式存放所要查询的数据,首先是表名,然后才是数据

    LOGI("...........database.......................row=%d,column=%d ,ret=%d",row,column,ret);

	sqlite3_free_table(result);//释放result的内存空间
	sqlite3_close(db); //关闭数据库


//要想访问系统的com.android.providers.media数据库,恐怕是不行的
       
ConcurrentModificationException java基础
//要么使用iterator的remove方法,像http://lggege.iteye.com/blog/249430
//要么使用CopyOnWriteArrayList或ConcurrentHashMap,像http://www.javacodegeeks.com/2011/05/avoid-concurrentmodificationexception.html

//异常产生的具体原因:http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html
concurrent定时任务--比Timer更精确? java, java基础
java.util.concurrent.Executors.newScheduledThreadPool(4)
				.scheduleAtFixedRate(new Runnable() {
					public void run() {
						 
							System.out.println("test");
					}
				}, 0, 100, TimeUnit.MILLISECONDS);//毫秒
		TimeUnit.NANOSECONDS;//纳秒
		TimeUnit.MICROSECONDS;//微秒
		TimeUnit.SECONDS;//秒
kryo--一个序列化工具 https://code.google.com/p/kryo/#Quickstart
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

public class test {

 
	public static void main(String[] args) {

		kryoTest();
	 
	}

	public static void kryoTest() {
		Kryo kryo = new Kryo();

		/* write */
		Output output = null;
		try {
			output = new Output(new FileOutputStream("d:/file.bin"));
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		People someObject = new People();
		someObject.age = 12;
		someObject.name = "jack";
		someObject.add = "china";

		kryo.writeObject(output, someObject);
		output.close();

		/* read */
		Input input = null;
		try {
			input = new Input(new FileInputStream("d:/file.bin"));
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		People outObject = kryo.readObject(input, People.class);
		input.close();
		System.out.println(outObject.birthday.year);
	}

	public static String bytes2HexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}

}

class People {
	public People() {
		birthday = new BirthDay();
		birthday.year = 2012;
		birthday.month = 7;
	}

	int age;
	String name;
	String add;
	BirthDay birthday;
}

class BirthDay {
	int year;
	int month;
}
java获取mp3文件的时长 http://my.oschina.net/gtd/blog/58172
//使用了jaudiotagger 这个库
public static int getMp3TrackLength(File mp3File) {
		try {
			MP3File f = (MP3File)AudioFileIO.read(mp3File);
			MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
			return audioHeader.getTrackLength();	
		} catch(Exception e) {
			return -1;
		}
	}
//getTrackLength函数返回的是秒数,最好转化为00:00这样的字符串
public static String parseSecondsToMinute(int duration){
		int minute= duration/60;
		int second= duration%60;
		String minuteString=""+minute;
		String secondString=""+second;
		if (minute<10) {
			minuteString="0"+minuteString;
		}
		if (second<10) {
			secondString="0"+secondString;
		}
		return minuteString+":"+secondString;
	}
Json-lib使用
json如下:{"rsp":{"pn":"0","totalResults":"2","items":[{"id":"2","name":"[软件][android]安卓市场","size":"1365","total":"0","type":"1","p_path":"http://m.epcool.com/soft/res/images/Himarket.jpg","r_path":"http://m.epcool.com/soft/res/Himarket_Android616_sj.apk","time":"2011-11-07"},{"id":"1","name":"[软件][android]360手机卫士","size":"1821","total":"8","type":"1","p_path":"http://m.epcool.com/soft/res/images/360logo.jpg","r_path":"http://m.epcool.com/soft/res/360MobileSafe.apk","time":"2011-06-29"}]}}


	String json = HttpDownload.getJSONData(Commons.APP_SHARE_RESOURCE_URL);
	//获取根节点 
	JSONObject root =  JSONObject.fromObject(jsonString);
	JSONObject rsp = root.getJSONObject("rsp");
	JSONArray items = rsp.getJSONArray("items");
	for (int i = 0; i < items.length(); i++) {
		AppShareResource share = new AppShareResource();
		share.setP_path(items.getJSONObject(i).getString("p_path"));
		share.setName(items.getJSONObject(i).getString("name"));
		share.setSize(items.getJSONObject(i).getString("size"));
		share.setTime(items.getJSONObject(i).getString("time"));
		share.setTotal(items.getJSONObject(i).getString("total"));
		list.add(share);
	}
其实也可以直接将json字符串转化为bean.这里只是提供一种用法.
对了,JSONObject的toString((int indentFactor)函数提供了将难看的json字符串转换成对人友好的字符串的功能,例如,上面的字符串,toString(2)的打印结果是:

{"rsp": {
    "pn": "0",
    "totalResults": "2",
    "items":     [
                {
            "id": "2",
            "name": "[软件][android]安卓市场",
            "size": "1365",
            "total": "0",
            "type": "1",
            "p_path": "http://m.epcool.com/soft/res/images/Himarket.jpg",
            "r_path": "http://m.epcool.com/soft/res/Himarket_Android616_sj.apk",
            "time": "2011-11-07"
        },
                {
            "id": "1",
            "name": "[软件][android]360手机卫士",
            "size": "1821",
            "total": "8",
            "type": "1",
            "p_path": "http://m.epcool.com/soft/res/images/360logo.jpg",
            "r_path": "http://m.epcool.com/soft/res/360MobileSafe.apk",
            "time": "2011-06-29"
        }
    ]
}}
这样看起来就清楚多啦.


JSONStringer类提供了一种比较直观的将java对象转化为json的方法:
JSONStringer jsonstringer = new JSONStringer();
    //创建第一个对象,可以理解为一个'{'创建一个object。对象1开始
    jsonstringer.object();       
    jsonstringer.key("copy");
    //copy对象的值还是一个对象,继续创建object.对象2开始
    jsonstringer.object();                       
    jsonstringer.key("terminal");
    //对象3开始
    jsonstringer.object();
    jsonstringer.key("vendor");
    jsonstringer.value(vendor);
    jsonstringer.key("model");
    jsonstringer.value(model);
    //对象3结束 对应字符'}'
    jsonstringer.endObject();               
    jsonstringer.key("file");
    //file对应的值为数组  对应字符'[',数组开始
    jsonstringer.array();         
            
    for(int i = 0; i<FileList.size();i++){
            jsonstringer.object();                       
            jsonstringer.key("info");
            jsonstringer.object();
            jsonstringer.key("srcfile");
            jsonstringer.value(FileList.get(i).SrcFileStr);       
            jsonstringer.key("dstdir");
            jsonstringer.value(FileList.get(i).DstDirStr);
            jsonstringer.endObject();                       
            jsonstringer.endObject();
    }
    //数组结束 对应字符']'
    jsonstringer.endArray();
    //对象2结束  对应字符'}'
    jsonstringer.endObject();
    //对象3结束,对应字符'}'
    jsonstringer.endObject();
java处理图片--白色处理为透明或半透明 java
package imges;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

class MyFilter
//extends RGBImageFilter 
{// 抽象类RGBImageFilter是ImageFilter的子类,

	// 继承它实现图象ARGB的处理

//	int alpha = 0;
//
//	static double i = 0;
//
//	public MyFilter(int alpha) {// 构造器,用来接收需要过滤图象的尺寸,以及透明度
//
//		this.canFilterIndexColorModel = true;
//		this.alpha = alpha;
//
//	}

//	public int filterRGB(int x, int y, int rgb) {
//		i++;
//		DirectColorModel dcm = (DirectColorModel) ColorModel.getRGBdefault();
//
//		// DirectColorModel类用来将ARGB值独立分解出来
//
//		int red = dcm.getRed(rgb);
//
//		int green = dcm.getGreen(rgb);
//
//		int blue = dcm.getBlue(rgb);
//
//		int alp = dcm.getAlpha(rgb);
//		if ((red == 255 && blue == 255 && green == 255) || alp == 0) {// 如果像素为白色,则让它透明
//			alpha = 0;
//
//		} else {
//
//			alpha = 255;
//
//		}
//		return alpha << 24 | red << 16 | green << 8 | blue;// 进行标准ARGB输出以实现图象过滤
//
//	}

//	public static void transform1() {
//		try {
//
//			BufferedImage imageBiao = ImageIO.read(new FileInputStream(
//					"d://test.png"));
//			Graphics2D g = imageBiao.createGraphics();
//
//			ImageFilter imgf = new MyFilter(255); // 白色
//
//			FilteredImageSource fis = new FilteredImageSource(
//					imageBiao.getSource(), imgf);
//
//			Image im = Toolkit.getDefaultToolkit().createImage(fis);
//
//			g.drawImage(im, 0, 0, imageBiao.getWidth(null),
//					imageBiao.getHeight(null), null);
//
//			g.dispose();
//
//			ImageIO.write(imageBiao, "png", new File("d://test2.png"));
//
//		} catch (Exception e) {
//
//			e.printStackTrace();
//
//		}
//	}

	public static void 半透明() {
		try {

			ImageIcon imageIcon = new ImageIcon("d://test.png");

			setAlpha(imageIcon);

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	public static void setAlpha(ImageIcon image) {
		/**
		 * 增加测试项 读取图片,绘制成半透明
		 */
		try {

			ImageIcon imageIcon = (image);
			BufferedImage bufferedImage = new BufferedImage(
					imageIcon.getIconWidth(), imageIcon.getIconHeight(),
					BufferedImage.TYPE_4BYTE_ABGR);
			Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
			g2D.drawImage(imageIcon.getImage(), 0, 0,
					imageIcon.getImageObserver());
			// 循环每一个像素点,改变像素点的Alpha值
			int alpha = 100;
			for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
					.getHeight(); j1++) {
				for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
						.getWidth(); j2++) {
					int rgb = bufferedImage.getRGB(j2, j1);
					rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
					bufferedImage.setRGB(j2, j1, rgb);

					 

				}
			}
			g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());

			// 生成图片为PNG

			ImageIO.write(bufferedImage, "png", new File("d://test2.png"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void 透明() {
		BufferedImage source = null;
		try {
			source = ImageIO.read(new FileInputStream("d://china.png"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final Color color = new Color(source.getRGB(0, 0));

		final ImageFilter filter = new RGBImageFilter() {
			// the color we are looking for (white)... Alpha bits are set to
			// opaque
			public int markerRGB = color.getRGB() | 0xFFFFFFFF;

			public final int filterRGB(final int x, final int y, final int rgb) {
				if ((rgb | 0xFF000000) == markerRGB) {
					// Mark the alpha bits as zero - transparent
					return 0x00FFFFFF & rgb;
				} else {
					// nothing to do
					return rgb;
				}
			}
		};

		final ImageProducer ip = new FilteredImageSource(source.getSource(),
				filter);
		Image image = Toolkit.getDefaultToolkit().createImage(ip);
		BufferedImage bufferedImage = imageToBufferedImage(image);
		try {
			ImageIO.write(bufferedImage, "png", new File("d://china2.png"));
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	private static BufferedImage imageToBufferedImage(final Image image) {
		final BufferedImage bufferedImage = new BufferedImage(
				image.getWidth(null), image.getHeight(null),
				BufferedImage.TYPE_INT_ARGB);
		final Graphics2D g2 = bufferedImage.createGraphics();
		g2.drawImage(image, 0, 0, null);
		g2.dispose();
		return bufferedImage;
	}

	public static void main(String[] args) {
		透明();

	}
}
python基本语法
#!/bin/env python
# coding=gb2312
# -*- coding: gb2312 -*-
from __future__ import division
#### if-else ####
print '#### if-else ####'
a = input("a: ") # 12 or 10+2
b = input("b: ")
if(a>b):
    print "max: ", a
else:
    print "max: ", b
#### if-elif-else ####
print '#### if-elif-else ####'
score = raw_input("score: ") # string
score = int(score)
if(score>=90) and (score<=100):
    print "A"
elif(score>=80 and score<90):
    print "B"
elif(score>=60 and score<80):
    print "C"
else:
    print "D"
#### switch  I ####
print '#### switch ####'
x = 1
y = 2
operator = "/"
result = {
    "+": x+y,
    "-": x-y,
    "*": x*y,
    "/": x/y
}
print result.get(operator)
#### switch II ####
print '#### switch II ####'
class switch(object):               
    def __init__(self, value):   # init value
        self.value = value
        self.fall = False        # no break, then fall=False    
    def __iter__(self):
        yield self.match         # match method to create 
        raise StopIteration      # exception to check loop
    def match(self, *args):
        if self.fall or not args:
            return True
        elif self.value in args: # successful
            self.fall = True
            return True
        else:                    # fail
            return False
operator = "+"
x = 1
y = 2
for case in switch(operator):
    if case('+'):
        print x+y
        break
    if case('-'):
        print x-y
        break
    if case('*'):
        print x*y
        break
    if case('/'):
        print x/y
        break
    if case():
        print 'NULL'

#### function ####
def add(a,b=2):
    return (a+b)

r=add(1)
print r
r=add(1,5)
print r
##################
输出XML内容 java, java基础 org.w3c.dom.Document对象与字符串互转
public static String docToString(Document doc) {     
        // XML转字符串      
        String xmlStr = "";     
        try {     
            TransformerFactory tf = TransformerFactory.newInstance();     
            Transformer t = tf.newTransformer();     
            t.setOutputProperty("encoding", "UTF-8");// 解决中文问题,试过用GBK不行      
            ByteArrayOutputStream bos = new ByteArrayOutputStream();     
            t.transform(new DOMSource(doc), new StreamResult(bos));     
            xmlStr = bos.toString();     
        } catch (TransformerConfigurationException e) {     
            // TODO Auto-generated catch block      
            e.printStackTrace();     
        } catch (TransformerException e) {     
            // TODO Auto-generated catch block      
            e.printStackTrace();     
        }     
        return xmlStr;     
    }  

//http://yangfei520.blog.51cto.com/1041581/382977
Global site tag (gtag.js) - Google Analytics