擷取狀態列和標題列的高度
擷取狀態列高度:
getWindowVisibleDisplayFrame方法可以擷取到程式顯示的地區,包括標題列,但不包括狀態列。
於是,我們就可以算出狀態列的高度了。
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
擷取標題列高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)這個方法擷取到的view就是程式不包括標題列的部分,然後就可以知道標題列的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的狀態列的高度
int titleBarHeight = contentTop - statusBarHeight
手機震動
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, -1);
需要在AndroidManifest.xml檔案添加許可權
<uses-permission android:name="android.permission.VIBRATE" />
擷取當前函數的函數名稱
Thread.currentThread().getStackTrace()[2].getMethodName();
設定單例模式
<activity android:name=".TT"
android:label="@string/app_name"
android:launchMode="singleTask">
列印當前函數的系統呼叫堆疊
java.util.Map<Thread, StackTraceElement[]> ts = Thread.getAllStackTraces(); StackTraceElement[] ste = ts.get(Thread.currentThread()); for (StackTraceElement s : ste) { Log.i(TAG, "StackTraceElement :"+s.toString()); }
擷取異常資訊的詳細
public static String getExceptionMessage(Exception ex){String result="";StackTraceElement[] stes = ex.getStackTrace();for(int i=0;i<stes.length;i++){result=result+stes[i].getClassName() + "." + stes[i].getMethodName() + " " + stes[i].getLineNumber() +"line"+"\r\n";}return result;}
當按返回鍵時,完全按退出系統
@Override protected void onDestroy() { // TODO Auto-generated method stub android.os.Process.killProcess(android.os.Process.myPid());//System.exit(0); super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); return true; } return super.onKeyDown(keyCode, event); }
使用startActivity應該處理各種情況跟異常!!!
void startActivitySafely(Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "not found activity", Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, "no permision start", Toast.LENGTH_SHORT).show(); e(LOG_TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity.", e); } }
設定透明背景,修改AndroidManifest.xml檔案,在對應的Activity裡面加上下面的屬性:
android:theme="@android:style/Theme.Translucent"
使用系統背景作為應用的背景,在onCreate的時候添加視窗標誌:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
判斷android裝置當前是否為案頭顯示
private ActivityManager mActivityManager;private List<String> homeList;/** * 判斷當前介面是否是案頭 */ public boolean isHome(){ if(mActivityManager == null) {mActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); } List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1); return homeList.contains(rti.get(0).topActivity.getPackageName()); } /** * 獲得屬於案頭的應用的應用程式套件名稱 * @return 返回包含所有包名的字串列表 */private List<String> getHomeApps() {List<String> names = new ArrayList<String>(); PackageManager packageManager = this.getPackageManager(); // 屬性 Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for(ResolveInfo ri : resolveInfo) { names.add(ri.activityInfo.packageName); } return names; }
許可權<uses-permission android:name="android.permission.GET_TASKS"/>
連續按兩次back鍵退出程式
long waitTime = 2000;long touchTime = 0;@Overridepublic void onBackPressed() {long currentTime = System.currentTimeMillis();if((currentTime-touchTime)>=waitTime) {Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();touchTime = currentTime;}else {finish();}}
返回系統案頭:
Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意 intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent);
Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//開闢新棧 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//清空棧內程式 startActivity(intent); //finish();
屏蔽home按鍵:
@Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }
在儲存卡上建立對應目錄:
File sdPath=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"AcerRemoteLog"); if(!sdPath.exists()){ sdPath.mkdirs(); } File logFile = new File(sdPath,format.format(new Date())+"AppLog"+".txt"); if(!logFile.exists()){ try { logFile.createNewFile();} catch (IOException e) {e.printStackTrace();} }
複製項目資源檔到本機存放區裝置:
private void copyResourceFile(int rid, String targetFile){ InputStream fin = ((Context)this).getResources().openRawResource(rid); FileOutputStream fos=null; int length;try {fos = new FileOutputStream(targetFile);byte[] buffer = new byte[1024*32]; while( (length = fin.read(buffer)) != -1){ fos.write(buffer,0,length); }} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{if(fin!=null){try {fin.close();} catch (IOException e) {e.printStackTrace();}} if(fos!=null){ try {fos.close();} catch (IOException e) {e.printStackTrace();} }} }
判斷字串是否為ip地址:
//match ip adressPattern p = Pattern.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])" +"\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])" +"\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");Matcher m = p.matcher(str_ip);if(m.matches()){//ip}else{//not ip}
圖片壓縮成流,byte數組
private static void toArray(Bitmap src, Bitmap.CompressFormat format, int quality) { ByteArrayOutputStream os = new ByteArrayOutputStream(); src.compress(format, quality, os); byte[] array = os.toByteArray(); // return BitmapFactory.decodeByteArray(array, 0, array.length); }
子線程內部建立訊息佇列
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
使用Linux shell命令類比按鍵資訊
/** * run linuix shell cmmand * @param keyCode */ private void runLinuixShell(final int keyCode){ try{ String keyCommand = "input keyevent " + keyCode; Runtime runtime = Runtime.getRuntime(); Process proc=runtime.exec(keyCommand); Log.e("cmdrun","keycode= "+keyCode); // proc.destroy(); }catch (IOException e){ Log.e("cmderror", e.toString()); } }
Linux shell命令檔案操作
1,建立目錄:
private void buildResource(String resourceDirectory) { String[] str ={"mkdir", resourceDirectory}; try { Process ps = Runtime.getRuntime().exec(str); try { ps.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
2,移除目錄:
private void clearResource(String resourceDirectory) { String[] str ={"rm", "-r", resourceDirectory}; try { Process ps = Runtime.getRuntime().exec(str); try { ps.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } }
計算字型寬度:
public static float GetTextWidth(String text, float Size) { TextPaint FontPaint = new TextPaint(); FontPaint.setTextSize(Size); return FontPaint.measureText(text); }
計算裝置尺寸:
public static double getScreenPhysicalSize(Activity ctx) { DisplayMetrics dm = new DisplayMetrics(); ctx.getWindowManager().getDefaultDisplay().getMetrics(dm); double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2)); return diagonalPixels / (160 * dm.density); }
判斷裝置是否為平板
public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; }