[英]How to relaunch app that listens to BOOT_COMPLETED
My app listens to BOOT_COMPLETED
to start. 我的应用程序监听
BOOT_COMPLETED
以启动。
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</receiver>
But if my app crashes, how could I get it to automatically restart? 但是,如果我的应用程序崩溃了,该如何自动重启?
BOOT_COMPLETED
is not a sticky intent. BOOT_COMPLETED
不是粘性的意图。
To get Answer of your question is very simple. 得到您的问题的答案很简单。 In that case you need to use Thread.setDefaultUncaughtExceptionHandler().
在这种情况下,您需要使用Thread.setDefaultUncaughtExceptionHandler()。 It will always enter in uncaughtException() in case your application crashed.For Check Full Tutorial Here
它会在情况uncaughtException()始终输入您的应用程序crashed.For 检查全教程这里
public class YourApplication extends Application {
private static Context mContext;
public static YourApplication instace;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
instace = this;
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static YourApplication getIntance() {
return instace;
}
}
DefaultExceptionHandler.java DefaultExceptionHandler.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
/**
* This custom class is used to handle exception.
*
* @author Chintan Rathod (http://www.chintanrathod.com)
*/
public class DefaultExceptionHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler defaultUEH;
Activity activity;
public DefaultExceptionHandler(Activity activity) {
this.activity = activity;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
Intent intent = new Intent(activity, RelaunchActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
YourApplication.getInstance().getBaseContext(), 0, intent, intent.getFlags());
//Following code will restart your application after 2 seconds
AlarmManager mgr = (AlarmManager) YourApplication.getInstance().getBaseContext()
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
pendingIntent);
//This will finish your activity manually
activity.finish();
//This will stop your application and take out from it.
System.exit(2);
} catch (IOException e) {
e.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.