Android restart app after clearing cache and data

江枫思渺然 提交于 2019-12-02 08:25:46

After calling clearApplication data, application is killed.Thats why MainActivity doesn't called.

Create new ApplicationClass like below

public class ApplicationClass extends Application {

private static ApplicationClass instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;
}

public static ApplicationClass getInstance() {
    return instance;
}
}

Add Application class to Application tag of manifest

android:name=".ApplicationClass"

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:name=".ApplicationClass"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And use this code for clearing data

Intent intent = new Intent(MainActivity.this, MainActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                 | Intent.FLAG_ACTIVITY_CLEAR_TASK
                 | Intent.FLAG_ACTIVITY_NEW_TASK);
         PendingIntent pendingIntent = PendingIntent.getActivity(ApplicationClass.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
         AlarmManager mgr = (AlarmManager) ApplicationClass.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
         mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
         System.exit(2);
         ((ActivityManager)MainActivity.this.getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
b devloper

For Clear cache try reference link

Try below code for restart app

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

Note: If you use clear the app data app doesn't restart. You have to restart it again manually.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!