Android常用代码片段

来源:互联网 发布:小脚趾内翻怎么办知乎 编辑:程序博客网 时间:2024/05/20 21:50

21.手机相册照片的方向是否需要旋转

    //可以读取相片的方向值,然后旋转读取方向值请参照下面的代码:      ExifInterface exifInterface = new ExifInterface(bitmapUrl);      int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);      然后旋转:      int degree = 0;      if (tag == ExifInterface.ORIENTATION_ROTATE_90)       {      degree = 90;      }       else if (tag == ExifInterface.ORIENTATION_ROTATE_180)       {      degree = 180;      }       else if (tag == ExifInterface.ORIENTATION_ROTATE_270)       {      degree = 270;      }      if (degrees != 0 && bitmap != null)       {          Matrix m = new Matrix();          m.setRotate(degrees, (float) bitmap.getWidth() / 2,           (float) bitmap.getHeight() / 2);      }  
20.得到状态栏的高度

Rect rectgle= new Rect();  Window window= getWindow();  window.getDecorView().getWindowVisibleDisplayFrame(rectgle);  int StatusBarHeight= rectgle.top;  int contentViewTop=           window.findViewById(Window.ID_ANDROID_CONTENT).getTop();  int TitleBarHeight= contentViewTop - StatusBarHeight;  Log.i("*** Jorgesys :: ", "StatusBar Height= " + StatusBarHeight + " , TitleBar Height = " + TitleBarHeight);

19.得到系统的语言和地区

    String s = Locale.getDefault().getLanguage();              String s2 = Locale.getDefault().getCountry();              System.out.println("Language: "+s+" Country: "+s2);              String locale = this.getResources().getConfiguration().locale.getDisplayName();              System.out.println("locale:"+locale);  

18.Bitmap与byte二进制数组互转
public byte[] getBitmapByte(Bitmap bitmap){         ByteArrayOutputStream out = new ByteArrayOutputStream();         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);         try {             out.flush();             out.close();         } catch (IOException e) {             e.printStackTrace();         }         return out.toByteArray();     }  //将byte转换成bitmap  public Bitmap getBitmapFromByte(byte[] temp){         if(temp != null){             Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);             return bitmap;         }else{             return null;         }     }
17.代码动态添加线性布局LinearLayout和按钮Button
    LinearLayout ll = new LinearLayout(this);              ll.setOrientation(LinearLayout.VERTICAL);              Button b1 = new Button(this);              b1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));              Button b2 = new Button(this);              b2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));              ll.addView(b1, 0);              ll.addView(b2, 1);  

16.检查apk文件
    public boolean checkApkFile(String apkFilePath) {                    boolean result = false;                    try{                        PackageManager pManager = getPackageManager();                        PackageInfo pInfo = pManager.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);                        if (pInfo == null) {                            result =  false;                        } else {                            result =  true;                        }                    } catch(Exception e) {                        result =  false;                        e.printStackTrace();                    }                    return result;                }  

15.安装apk文件
    public void install(File apkFile){            Uri uri = Uri.fromFile(apkFile);                    Intent intent = new Intent(Intent.ACTION_VIEW);                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                    intent.setDataAndType(uri, "application/vnd.android.package-archive");                    startActivity(intent);                }  

14.Android Handler延时发送线程队列code

    public class MainActivity extends Activity {                Handler handler =new Handler();          @Override          public void onCreate(Bundle savedInstanceState) {              super.onCreate(savedInstanceState);              setContentView(R.layout.activity_main);              handler.postDelayed(runnable, 3000);          }                    //跳转线程          Runnable runnable = new Runnable() {              @Override              public void run() {                  Intent intent = new Intent(MainActivity.this, SlidDraw1.class);                  startActivity(intent);              }          };      }  

13.ListView Cascade Animation

    /**          * Animation ListView Cascade瀑布          */          protected void animationListView(ListView listView){              AnimationSet set = new AnimationSet(true);                            Animation animation = new AlphaAnimation(0.0f,1.0f);              animation.setDuration(50);              set.addAnimation(animation);                            animation = new TranslateAnimation(                  Animation.RELATIVE_TO_SELF,0.0f,Animation.RELATIVE_TO_SELF,0.0f,                  Animation.RELATIVE_TO_SELF,-1.0f,Animation.RELATIVE_TO_SELF,0.0f              );              animation.setDuration(100);              set.addAnimation(animation);                            LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);              listView.setLayoutAnimation(controller);          }  

12.文件下载

 ①java

    class DownThread implements Runnable{                    @Override              public void run() {                  try {                      Log.v(Constants.LOG_TAG, " begin run");                      URL downurl = new URL(example_url);                      URLConnection connection =  downurl.openConnection();                      connection.connect();                      int fileLength = connection.getContentLength();//Returns the value of the content-length header field      //              InputStream ins = new BufferedInputStream(downurl.openStream());                      InputStream ins = downurl.openStream();// 上面的那个办法已经有一个缓存,下面又自定义了一个缓存,多此一举。直接读取输入流放入自定义缓存                      OutputStream ous = new FileOutputStream("/sdcard/adown.mp3");                      Log.v(Constants.LOG_TAG, " length "+fileLength);                      byte[] buf = new byte[8192];                      long total = 0;                      int count;                      while((count = ins.read(buf)) != -1){                          total += count;                          int p = (int)(total * 100 / fileLength);                          ous.write(buf, 0, count);                          Log.v(Constants.LOG_TAG, " read bytes- "+ count);                          handler.sendEmptyMessage(p);                      }                      ous.flush();                      ous.close();                      ins.close();                  } catch (MalformedURLException e) {                      e.printStackTrace();                  } catch (IOException e) {                      e.printStackTrace();                  }                                }                        }  

②android

    class DownloadThread2 extends Thread{              public void run(){                  HttpClient client = new DefaultHttpClient();                  HttpGet get = new HttpGet(example_url);                  HttpResponse response;                  try {                      response = client.execute(get);                      HttpEntity entity = response.getEntity();                      long fileLength = entity.getContentLength();                      InputStream is = entity.getContent();                      FileOutputStream fos = null;                      long total = 0;                      if(is != null){                          final String f = SDCardUtil.getFileNamefromUrl(example_url);                          File file = new File(SDCardUtil.makeDir(DOWNLOADDIR)+File.separator+f);                          fos = new FileOutputStream(file);                          byte[] buf = new byte[1024];                          int ch = -1;                          int count = 0;                          while((count = is.read(buf)) != -1){                              fos.write(buf,0,count);                              total += count;                              int p = (int)(total * 100 / fileLength);                              Log.v(Constants.LOG_TAG, " progress- "+p);                              handler.sendEmptyMessage(p);                          }                      }                      fos.flush();                      if(fos != null){                          fos.close();                      }                  } catch (Exception e) {                      e.printStackTrace();                  }              }          }  
11.纯代码逐帧动画
<pre name="code" class="java">    public void onClick(View v) {                      AnimationDrawable anim = new AnimationDrawable();                      for (int i = 58; i <= 68; i++) {                          int id = getResources().getIdentifier("loadingblack" + i, "drawable", getPackageName());                          Drawable drawable = getResources().getDrawable(id);                          anim.addFrame(drawable, 300);                      }                      anim.setOneShot(false);                      image.setBackgroundDrawable(anim);                      anim.start();                  }  


8.判断SDCard的状态

自定义的一个方法判断SDCard的当前状态,参考的API文档。

访问SD卡权限切记<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    /**          * 判断SDCard的状态。          * @return 2:读、写;1:只读;0:不可读不可写          */          public int isSDCardAvailable(){              String state = Environment.getExternalStorageState();                    if (Environment.MEDIA_MOUNTED.equals(state)) {                  // We can read and write the media                  return 2;              } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {                  // We can only read the media                  return 1;              } else {                  // Something else is wrong. It may be one of many other states, but all we need                  // to know is we can neither read nor write                  return 0;              }                        }  

7.判断是否联网

if判断条件中第二个条件也可以用netInfo.isConnected();

    /**          * 判断网络是否连通          */          private void judgeNetwork() {              /*              * The primary responsibilities of this class(ConnectivityManager) are              * to:               * 1.Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)               * 2.Send broadcast intents when network connectivity changes               * 3.Attempt to "fail over" to another network when connectivity to a network is lost              * 4.Provide an API that allows applications to query the coarse-grained              * or fine-grained state of the available networks              * 千万不要忘了在manifest里面加个权限 ,粗心的朋友一定要记住:              * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>              */              ConnectivityManager conman = (ConnectivityManager) this                      .getSystemService(Context.CONNECTIVITY_SERVICE);                    NetworkInfo netInfo = conman.getActiveNetworkInfo();                    if (netInfo != null && netInfo.isAvailable()) {// 可以联网                  Toast.makeText(this, "OK网!", Toast.LENGTH_SHORT).show();              } else {                  Toast.makeText(this, "貌似断网了!", Toast.LENGTH_SHORT).show();              }          }  

1.获取屏幕宽度和高度

    WindowManager wm=getWindowManager();      Display    dp=wm.getDefaultDisplay();      System.out.println(dp.getWidth());      System.out.println(dp.getHeight());      Toast.makeText(this,dp.getWidth()+"=="+dp.getHeight(),  3000).show();  

2.去除标题栏和状态栏(全屏)

    //取消标题      this.requestWindowFeature(Window.FEATURE_NO_TITLE);      //取消状态栏      this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,           WindowManager.LayoutParams.FLAG_FULLSCREEN);  

 或者在Manifest文件中修改:(android:theme="@android:style/Theme.NoTitleBar.Fullscreen",如果想只是去除标题栏就后面不用加Fullscreen了,另外,如果想要整个应用都去除标题栏和状态栏,就把这句代码加到<application。。标签里面,如果只是想某个activity起作用,这句代码就加到相应的activity上):

3.获取SDcard路径

访问SD卡权限切记<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
/ 2.1以及以前的版本用这个获取SDCARD,保存缓存文件等          File mResPath = Environment.getExternalStorageDirectory();//Environment是android.os.Environment包中的类          Log.i(CLASS_TAG, " "+mResPath); // 获取SDCARD根目录/mnt/sdcard          System.out.println(this.getExternalFilesDir(null).toString());// 获取files的绝对路径          System.out.println(this.getExternalCacheDir().toString());// 获取cache的绝对路径          System.out.println(this.getFilesDir().toString());// 获取files的相对路径 

5.判断字符串是不是数字

//isNumeric();判断参数是不是一个数字,返回值boolean型  private boolean isNumeric(String s) {          try {              Integer.parseInt(s);          } catch (NumberFormatException e) {              return false;          } catch (NullPointerException e) {              return false;          }          return true;  }  




0 0
原创粉丝点击