android代码片段整理,持续更新中。。。。。。

   一.http连接

          httpclient的Get请求:

          String  httpUrl = "www.baidu.com";   
                HttpClient httpClient = new DefaultHttpClient();  
                HttpGet httpRequest = new HttpGet(httpUrl);  
                try {  
                    HttpResponse httpResponse =httpClient.execute(httpRequest);  
                    if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
                        String strResult = EntityUtils.toString(httpResponse.getEntity());  
                    }  
                } catch (ClientProtocolException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
             httpclient的post请求:
  HttpClient httpClient = null ;  
  HttpPost httpRequest = null ;  
  HttpResponse httpResponse = null ;  
  try {  
  httpUrl = "http://192.168.1.7:8080/exa/index.jsp";  
  // 取得默认的 HttpClient  
  httpClient = new DefaultHttpClient();  
  // HttpPost 连接对象  
  httpRequest = new HttpPost(httpUrl);  
  // 使用 NameValuePair 来保存要传递的 Post 参数  
  List<NameValuePair> params = new ArrayList<NameValuePair>();  
  // 添加要传递的参数  
  new  
  params.add(new BasicNameValuePair("testParam1", "110"));  
  // 设置字符集  
  HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  
  // 请求 httpRequest  
  httpRequest.setEntity(httpentity);  
  // 取得 HttpResponse  
  httpResponse = httpClient.execute(httpRequest);  
  // HttpStatus.SC_OK 表示连接成功  
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  // 取得返回的字符串  
  String strResult = EntityUtils.toString(httpResponse  
  .getEntity());  
  textView_1.setText(strResult);  
  }  
 } catch (Exception e) {  
  e.printStackTrace();  
  } finally {  
 } 

 二.Android开机启动应用:

   启动广播监听系统发出的开机广播,注:有些手机必须先在安全设置中授权一下允许应用自启动
    public class StartupReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
                //xxx 你要跳转到的activity	也可以是Service	
                Intent i = new Intent(context,xxx.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//将intent以startActivity传送给操作系统
		context.startActivity(i);
	}
}
在AndroidManifest.xml中注册广播:
      <receiver android:name=".StartupReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" />  
                <category android:name="android.intent.category.HOME" />  
            </intent-filter>  
        </receiver>
添加权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
三.Toast连续点击只显示一次
在平时开发中会用到Toast,连续点击后会不断弹出Toast,很影响体验,现在实现连续点击只显示当前的,
	private static Toast toast = null;
	public static void showToast(Context act, String text, int duration) {
		if (toast != null) {
			toast.setText(text);
			toast.setDuration(duration);
			toast.show();
		} else {
			toast = Toast.makeText(act, text, duration);
			toast.show();
		}
	}
四.判断当前网络是否可用
public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService
                         (Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null && info.isConnected()) {
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}
Or:
public static boolean isOpenNetwork(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		}
		return false;
	}
 
 五:保存BitMap到当前目录: 
	public static void saveBitmap(Bitmap bm) {
		try {
			FileOutputStream out = new FileOutputStream(
					Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
			bm.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

六:读取asset下的文件:
      public static String readFileTest(Context context, String asset) throws IOException {
		File mAppDirectory = context.getExternalFilesDir(null);
		InputStream source = context.getAssets().open(new File(asset).getPath());
		File destinationFile = new File(mAppDirectory, asset);
		destinationFile.getParentFile().mkdirs();
		OutputStream destination = new FileOutputStream(destinationFile);
		String modelpath = destinationFile.getParentFile().getAbsolutePath().toString();
		byte[] buffer = new byte[1024];
		int nread;
		while ((nread = source.read(buffer)) != -1) {
			if (nread == 0) {
				nread = source.read();
				if (nread < 0)
					break;
				destination.write(nread);
				continue;
			}
			destination.write(buffer, 0, nread);
		}
		destination.close();
		return modelpath;
	}
七:请求数据时等待控件:
public class LoadDialogDao 
{
	private Context mContext = null;
	ProgressDialog load = null;
	public LoadDialogDao(Context context,String msg) 
	{
		super();
		mContext = context;
		load = new ProgressDialog(mContext);
		load.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		load.setMessage(msg);
		load.setIndeterminate(false);
		load.setCancelable(true);
		load.setCanceledOnTouchOutside(false);
	}
	
	public void ChangeDlgMsg(String msg)
	{
		load.setMessage(msg);
	}
	
	public void show()
	{
		load.show();
		
	}
	
	public void hide()
	{
		load.dismiss();
	}
	
	public void error(String err)
	{
		Toast.makeText(mContext,(CharSequence)err, Toast.LENGTH_LONG).show();
		this.hide();
	}
}
显示时调用:
 LoadDialogDao	lDialog = new LoadDialogDao(MainActivity.this, "正在请求中...");
 lDialog.show();
隐藏时调用:
 lDialog.hide();
八:保留五位小数:
    public static String TranslateStringCode(String scored) {
		float f = Float.parseFloat(scored);
		BigDecimal bg = new BigDecimal(f);
		double f1 = bg.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
		String finalcore = String.valueOf(f1);
		return finalcore;
	}
九:Yuv压缩图片:
public static void dealWithImage(byte[] imagedata, int iwidth, int iheight) {
		ByteArrayOutputStream img = new ByteArrayOutputStream();
		YuvImage yuvimage = new YuvImage(imagedata, ImageFormat.NV21, iwidth, iheight, null);
		yuvimage.compressToJpeg(new Rect(0, 0, iwidth, iheight), 85, img);
	}
十:保存图片为灰色图片:
public static void saveDirGrayImage(byte[] imageData, int width, int height) {
		try {
			Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
			for (int i = 0; i < height; i++) {
				for (int j = 0; j < width; j++) {
					int value = imageData[i * width + j];
					int color = (value << 16) | (value << 8) | value | 0xFF000000; // RGB_565??��??
					bitmap.setPixel(j, i, color);
				}
			}
			Matrix matrix = new Matrix();
			matrix.postRotate(0.0f);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
			bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
			FileOutputStream out = new FileOutputStream(
					Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + ".jpg");
			bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
十一:相机获得最接近屏幕分辨率:
public static String getSize(Camera.Parameters parameters, Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		int screenWidth = display.getWidth();
		int screenHeight = display.getHeight();
		List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
		int[] a = new int[sizes.size()];
		int[] b = new int[sizes.size()];
		for (int i = 0; i < sizes.size(); i++) {
			int supportH = sizes.get(i).height;
			int supportW = sizes.get(i).width;
			a[i] = Math.abs(supportW - screenHeight);
			b[i] = Math.abs(supportH - screenWidth);
			Log.d("test", "supportW:" + supportW + "supportH:" + supportH);
		}
		int minW = 0, minA = a[0];
		for (int i = 0; i < a.length; i++) {
			if (a[i] <= minA) {
				minW = i;
				minA = a[i];
			}
		}
		int minH = 0, minB = b[0];
		for (int i = 0; i < b.length; i++) {
			if (b[i] < minB) {
				minH = i;
				minB = b[i];
			}
		}
		String s = "宽度" + sizes.get(minW).width + "高度" + sizes.get(minW).height;
		return s;
	}

十二:dip转px
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}
十三:px转dip
<span style="white-space:pre">	</span>public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
十四:获取屏幕宽度和高度
       DisplayMetrics dm = context.getResources().getDisplayMetrics();
	int w_screen = dm.widthPixels;
	int h_screen = dm.heightPixels;
	Log.i(TAG, "Screen---Width = " + w_screen + " Height = " + h_screen + " densityDpi = " + dm.densityDpi);
	return new Point(w_screen, h_screen);
十五:获取屏幕长宽比
<span style="white-space:pre">	</span>Point P = getScreenMetrics(context);
		float H = P.y;
		float W = P.x;
		return (H / W);</span>
 
 十六:Camera手机支持的预览尺寸: 
public  void printSupportPreviewSize(Camera.Parameters params){
		List<Size> previewSizes = params.getSupportedPreviewSizes();
		for(int i=0; i< previewSizes.size(); i++){
			Size size = previewSizes.get(i);
			Log.i(TAG, "previewSizes:width = "+size.width+" height = "+size.height);
		}
	
	}
十七:Camera支持的相片尺寸:

public  void printSupportPictureSize(Camera.Parameters params){
		List<Size> pictureSizes = params.getSupportedPictureSizes();
		for(int i=0; i< pictureSizes.size(); i++){
			Size size = pictureSizes.get(i);
			Log.i(TAG, "pictureSizes:width = "+ size.width
					+" height = " + size.height);
		}
	}
十八:支持的聚焦模式:
public void printSupportFocusMode(Camera.Parameters params){
		List<String> focusModes = params.getSupportedFocusModes();
		for(String mode : focusModes){
			Log.i(TAG, "focusModes--" + mode);
		}
	}
十九:获得支持的尺寸,避免预览引起的变形:

	public  Size getPropPreviewSize(List<Camera.Size> list, float th, int minWidth){
		Collections.sort(list, sizeComparator);

		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).width == 1280 && list.get(i).height == 720) {
				return list.get(i);
			}
		}
		int i = 0;
		for(Size s:list){
			if((s.width >= minWidth) && equalRate(s, th)){
				Log.i(TAG, "PreviewSize:w = " + s.width + "h = " + s.height);
				break;
			}
			i++;
		}
		if(i == list.size()){
			i = 0;//如果没找到,就选最小的size
		}
		return list.get(i);
	}
	public Size getPropPictureSize(List<Camera.Size> list, float th, int minWidth){
		Collections.sort(list, sizeComparator);

		int i = 0;
		for(Size s:list){
			if((s.width >= minWidth) && equalRate(s, th)){
				Log.i(TAG, "PictureSize : w = " + s.width + "h = " + s.height);
				break;
			}
			i++;
		}
		if(i == list.size()){
			i = 0;//如果没找到,就选最小的size
		}
		return list.get(i);
	}

	public boolean equalRate(Size s, float rate){
		float r = (float)(s.width)/(float)(s.height);
		if(Math.abs(r - rate) <= 0.03)
		{
			return true;
		}
		else{
			return false;
		}
	}

	public  class CameraSizeComparator implements Comparator<Camera.Size>{
		public int compare(Size lhs, Size rhs) {
			// TODO Auto-generated method stub
			if(lhs.width == rhs.width){
				return 0;
			}
			else if(lhs.width > rhs.width){
				return 1;
			}
			else{
				return -1;
			}
		}

	}
调用方法:

getPropPreviewSize(mParams.getSupportedPreviewSizes(), previewRate,800);

mParams.getSupportedPreviewSizes得到支持的所有预览尺寸

previewRate为屏幕长宽比

800是最小宽度, 如果没有合适的,则选择这个
二十:字符串为空判断

public static  boolean isEmpty(String str)
	{
		if(str == null || str.trim().length() == 0)
		{
			return true ;
		}
		return false ;
	}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值