如何在关闭后使用" pm clear命令重新启动应用程序"

时间:2017-04-05 09:02:23

标签: android

我必须实现一个必须删除我的Android应用程序的所有用户/缓存数据的函数,为此我已经实现了一个我可以"调用"使用下面运行此代码的简单推送:

String performClearData() throws JSONException {
    JSONObject jdata = new JSONObject();
    try {
        FilesUtilities fu = new FilesUtilities();
        fu.deleteFiles();

        Runtime runtime = Runtime.getRuntime();
        runtime.exec("pm clear MY.APP");
        jdata.put("Stato del comando", "Eseguito");
    } catch (Exception e) {
        wil.WriteFile("warning", "5)PushResponderEngine - Exception in PerformClearData: " + e.toString());
    }
    return jdata.toString();
}

现在我知道是否可以在此命令后重新启动应用程序,我已尝试使用此代码但不起作用:

intent = PendingIntent.getActivity(MYApplication.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);

1 个答案:

答案 0 :(得分:1)

编辑:

在StartActivity.java中,必须在onCreate()方法中设置Thread.setDefaultUncaughtExceptionHandler(handler),如下所示:

public class StartActivity extends Activity {

final Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.context = context;
    setContentView(R.layout.start_activity);
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            StartActivity.restartApp(context);
        }
    });
    //your code here
}

public static void restartApp(Context context)
{
    Intent mStartActivity = new Intent(context, StartActivity.class); //Replace StartActivity with the name of the first activity in your app
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);
}

}

当你调用android pm clear data命令时,你强制关闭应用程序(如果它被打开); when the app gets force closed, it throws an unhandledException,由上面的代码处理。