应用重启

方法1:

Intent mStartActivity = new Intent(this, MainActivity.class);int mPendingIntentId = 123456;PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId,mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 5*1000, mPendingIntent);//System.exit(0);android.os.Process.killProcess(android.os.Process.myPid());

方法2:

 Intent i = getBaseContext().getPackageManager()                  .getLaunchIntentForPackage(getBaseContext().getPackageName());          i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);          startActivity(i);

手机振动
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);        }    }


判断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();}}

返回系统桌面:
ntent 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();
}

复制项目资源文件到本地存储设备:
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);         } 


检查有没有应用程序来接受处理你发出的intent

 public static boolean isIntentAvailable(Context context, String action) {        final PackageManager packageManager = context.getPackageManager();        final Intent intent = new Intent(action);        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);        return list.size() > 0;    }


检测字符串中是否包含汉字

public static boolean checkChinese(String sequence) {        final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";        boolean result = false;        Pattern pattern = Pattern.compile(format);        Matcher matcher = pattern.matcher(sequence);        result = matcher.find();        return result;    }


媒体库数据更新:

 public static void newFileNotify(String path) {        if (Defaults.do_mediascanner_notify) {            Log.d(TAG, "Notifying others about new file: " + path);            new MediaScannerNotifier(Globals.getContext(), path);        }    }    public static void deletedFileNotify(String path) {        // This might not work, I couldn't find an API call for this.        if (Defaults.do_mediascanner_notify) {            Log.d(TAG, "Notifying others about deleted file: " + path);            new MediaScannerNotifier(Globals.getContext(), path);        }    }    // A class to help notify the Music Player and other media services when    // a file has been uploaded.    private static class MediaScannerNotifier implements MediaScannerConnectionClient {        private final MediaScannerConnection connection;        private final String path;        public MediaScannerNotifier(Context context, String path) {            this.path = path;            connection = new MediaScannerConnection(context, this);            connection.connect();        }        public void onMediaScannerConnected() {            connection.scanFile(path, null); // null: we don't know MIME type        }        public void onScanCompleted(String path, Uri uri) {            connection.disconnect();        }    }

或者

// Tell the media scanner about the new file so that it is            // immediately available to the user.            MediaScannerConnection.scanFile(this,                    new String[] { file.toString() }, null,                    new MediaScannerConnection.OnScanCompletedListener() {                public void onScanCompleted(String path, Uri uri) {                    Log.i("ExternalStorage", "Scanned " + path + ":");                    Log.i("ExternalStorage", "-> uri=" + uri);                }            });

保持网络唤醒:

 private void takeWakeLock() {        if (wakeLock == null) {            Log.d(TAG, "About to take wake lock");            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);            // Many (all?) devices seem to not properly honor a            // PARTIAL_WAKE_LOCK,            // which should prevent CPU throttling. This has been            // well-complained-about on android-developers.            // For these devices, we have a config option to force the phone            // into a            // full wake lock.            if (fullWake) {                Log.d(TAG, "Need to take full wake lock");                wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, WAKE_LOCK_TAG);            } else {                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);            }            wakeLock.setReferenceCounted(false);        }        Log.d(TAG, "Acquiring wake lock");        wakeLock.acquire();    }    private void releaseWakeLock() {        Log.d(TAG, "Releasing wake lock");        if (wakeLock != null) {            wakeLock.release();            wakeLock = null;            Log.d(TAG, "Finished releasing wake lock");        } else {            Log.e(TAG, "Couldn't release null wake lock");        }    }    private void takeWifiLock() {        Log.d(TAG, "Taking wifi lock");        if (wifiLock == null) {            WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);            wifiLock = manager.createWifiLock("SwiFTP");            wifiLock.setReferenceCounted(false);        }        wifiLock.acquire();    }    private void releaseWifiLock() {        Log.d(TAG, "Releasing wifi lock");        if (wifiLock != null) {            wifiLock.release();            wifiLock = null;        }    }


开启移动网络

//打开或关闭GPRS       private boolean gprsEnabled(boolean bEnable)      {          Object[] argObjects = null;                            boolean isOpen = gprsIsOpenMethod("getMobileDataEnabled");          if(isOpen == !bEnable)          {              setGprsEnable("setMobileDataEnabled", bEnable);          }                    return isOpen;        }            //检测GPRS是否打开       private boolean gprsIsOpenMethod(String methodName)      {          Class cmClass       = mCM.getClass();          Class[] argClasses  = null;          Object[] argObject  = null;                    Boolean isOpen = false;          try          {              Method method = cmClass.getMethod(methodName, argClasses);                isOpen = (Boolean) method.invoke(mCM, argObject);          } catch (Exception e)          {              e.printStackTrace();          }            return isOpen;      }            //开启/关闭GPRS       private void setGprsEnabled(String methodName, boolean isEnable)      {          Class cmClass       = mCM.getClass();          Class[] argClasses  = new Class[1];          argClasses[0]       = boolean.class;                    try          {              Method method = cmClass.getMethod(methodName, argClasses);              method.invoke(mCM, isEnable);          } catch (Exception e)          {              e.printStackTrace();          }      }  

AndroidManifest.xml里添加权限:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission>

防止apk被反编译:

// 将此函数添加到要防止被反编译的类中即可!// 注意:1.for 循环不可用 do{}while(false) 的形式来代替,否则无效!//    2.a[0 - i] = 0; 数组下标必须为数值计算(0 - i)的形式,否则无效!private static void // static 最好保留以防被优化掉此函数AntiDecompile(){    char a[] = { 0 };    for( int i = 0;              i < 1;              i++ )    {         a[0 - i] = 0;    }}






更多相关文章

  1. Android桌面快捷方式的实现
  2. (android图像处理)android之bitmap各种常用函数
  3. Android jni调用,实现自己的JNI_OnLoad函数
  4. android 按home键返回到桌面后,再按桌面应用图标又重新打开该应用
  5. 【简单的学生管理界面】Android的if语句中有字符串判断
  6. android实现json数据的解析和把数据转换成json格式的字符串
  7. Android中SensorManager.getRotationMatrix函数:计算出旋转矩阵,
  8. Android JNI(实现自己的JNI_OnLoad函数)
  9. Android 时间字符串 转成UTC时间转为指定时间的时间字符串

随机推荐

  1. Android(安卓)Jetpack 系列篇(二) WorkMa
  2. Android 学习笔记-2010年10月
  3. android沉浸式状态栏和虚拟按键
  4. 教程:实现Android的不同精度的定位(基于网
  5. Android Studio 几个非常有用的工具
  6. Android里面WebView加载HTML里面点击按钮
  7. Android 保存浏览记录 SharedPreTools
  8. (翻译)VectorDrawables的使用
  9. android下TTS的传感器切换听筒和扬声器测
  10. Android实用代码片段(二)