有些時候我們會想要讓我們的應用關閉,通常做法如下:
1:通過拿到當前的程式 id ,呼叫 shell 命令,殺死程式
int
pid = android.os.Process.myPid();
String command = "kill -9 "+ Process.myPid();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String command = "kill -9 "+ Process.myPid();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2:呼叫系統的方法,殺死程式
android.os.Process.killProcess(android.os.Process.myPid());
3:呼叫系統的介面,退出應用。
System.exit(0);同樣有的時候在收到系統傳送的廣播或者其他操作時我們想要啟動我們的應用;
1 . 獲得包名,重啟應用
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage("com.android.nfc")
2. 重啟應用的activity
Intent k = context.getPackageManager().getLaunchIntentForPackage("com.android.nfc");k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(k);
3.設定定時任務重啟
Intent intent1 = MyApplication.getContext().getPackageManager().
getLaunchIntentForPackage(MyApplication.getContext().getPackageName());
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, intent1,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr= (AlarmManager)MyApplication.getContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000,restartIntent); // 3秒鐘後重啟應用
getLaunchIntentForPackage(MyApplication.getContext().getPackageName());
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, intent1,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr= (AlarmManager)MyApplication.getContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000,restartIntent); // 3秒鐘後重啟應用