Obtain the height of the status bar and title bar.
Retrieve the status bar height:
The getwindowvisibledisplayframe method can obtain the display area of the program, including the title bar, but not the status bar.
So we can calculate the height of the status bar.
Rect frame = new rect ();
Getwindow (). getdecorview (). getwindowvisibledisplayframe (FRAME );
Int statusbarheight = frame. Top;
Obtain the title bar height:
The view obtained by the getwindow (). findviewbyid (window. id_android_content) method is the part of the title bar that the program does not contain. Then you can know the height of the title bar.
Int contenttop = getwindow (). findviewbyid (window. id_android_content). gettop ();
// Statusbarheight is the height of the status bar requested above
Int titlebarheight = contenttop-statusbarheight
Mobile phone Vibration
Vibrator vibrator = (vibrator) getsystemservice (context. vibrator_service );
Vibrator. vibrate (pattern,-1 );
You need to add permissions to the androidmanifest. xml file.
<Uses-Permission Android: Name = "android. Permission. Vibrate"/>
Obtains the name of the current function.
Thread. currentthread (). getstacktrace () [2]. getmethodname ();
Set Singleton Mode
<Activity Android: Name = ". tt"
Android: Label = "@ string/app_name"
Android: launchmode = "singletask">
Print the system call stack of the current function
java.util.Map<Thread, StackTraceElement[]> ts = Thread.getAllStackTraces(); StackTraceElement[] ste = ts.get(Thread.currentThread()); for (StackTraceElement s : ste) { Log.i(TAG, "StackTraceElement :"+s.toString()); }
Obtain exception details
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;}
When you press the return key, completely press to exit the system
@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 should be used to handle various situations and exceptions !!!
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); } }
Set the transparent background, modify the androidmanifest. xml file, and add the following attributes to the corresponding activity:
Android: theme = "@ Android: style/theme. translucent"
Use the system background as the background of the application, and add the window flag during oncreate:
Getwindow (). addflags (windowmanager. layoutparams. flag_show_wallpaper );
Determine whether the Android device is currently displayed on the desktop
Private activitymanager mactivitymanager; private list <string> homelist;/*** determines whether the current interface is a desktop */Public Boolean ishome () {If (mactivitymanager = NULL) {mactivitymanager = (activitymanager) getsystemservice (context. activity_service);} List <runningtaskinfo> RRTI = mactivitymanager. getrunningtasks (1); Return homelist. contains (rrps. get (0 ). topactivity. getpackagename ();}/*** get the application package name of the desktop application * @ return returns the string list containing all Package Names */private list <string> gethomeapps () {list <string> names = new arraylist <string> (); packagemanager = This. getpackagemanager (); // property 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 ;}
Permission <uses-Permission Android: Name = "android. Permission. get_tasks"/>
Press the back key twice to exit the program.
Long waittime = 2000; long touchtime = 0; @ overridepublic void onbackpressed () {long currenttime = system. currenttimemillis (); If (currenttime-touchtime)> = waittime) {toast. maketext (this, "Quit again", toast. length_short ). show (); touchtime = currenttime;} else {finish ();}}
Back to system desktop:
Intent intent = new intent (intent. action_main); intent. setflags (intent. flag_activity_new_task); // note 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); // opens up a new stack intent. setflags (intent. flag_activity_clear_top); // clear the program startactivity (intent) in the stack; // finish ();
Shield The Home button:
@Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }
Create a directory on the storage card:
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();} }
Copy the project resource file to a local storage device:
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();} }} }
Judge whether the string is an IP Address:
//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}
Compress images into streams, byte Arrays
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); }
Establishes a message queue in a subthread.
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(); } }
Simulate button information using Linux shell commands
/** * 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 Command File Operations
1. Create a directory:
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. Remove the directory:
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(); } }
Calculate the font width:
public static float GetTextWidth(String text, float Size) { TextPaint FontPaint = new TextPaint(); FontPaint.setTextSize(Size); return FontPaint.measureText(text); }
Device size calculation:
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); }
Determine whether the device is a tablet
public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; }