Android 自動重啟

新接手的APP有自動重啟的功能

一直眼殘找不到重啟功能的Code

只好再stackoverflow一下

還真的找到一樣的方法 XD

法1 (還沒試)

Android: How to auto-restart application after it's been “force closed”?link
1
2
3
4
5
6
7
8

intent = PendingIntent.getActivity(YourApplication.getInstance().getBaseContext(), 0,
new Intent(getIntent()), getIntent().getFlags());

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
System.exit(2);

法2

發生Exceptione過後,再去handle他

Android App Restarts upon Crash/force closelink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

public class MyExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {

private final Context myContext;
private final Class<?> myActivityClass;

public MyExceptionHandler(Context context, Class<?> c) {

myContext = context;
myActivityClass = c;
}

public void uncaughtException(Thread thread, Throwable exception) {

StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
System.err.println(stackTrace);// You can use LogCat too
Intent intent = new Intent(myContext, myActivityClass);
String s = stackTrace.toString();
//you can use this String to know what caused the exception and in which Activity
intent.putExtra("uncaughtException",
"Exception is: " + stackTrace.toString());
intent.putExtra("stacktrace", s);
myContext.startActivity(intent);
//for restarting the Activity
Process.killProcess(Process.myPid());
System.exit(0);
}
}

Register

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
        YourCurrentActivity.class));

Trigger

// Throw Exception
throw new NullPointerException("Crash Test");