Android restart app by service

1. Register the restart service by adding the following in the application tag in your AndroidManifest file.

<service
    android:process=":restartservice"
    android:name=".services.RestartService"
    android:exported="false" />

2. Create a folder services in your root package, and then create the java class RestartService.java

public class RestartService extends IntentService {
    public RestartService() {
        super("RestartService");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();
        for (int i = 0; i < runningAppProcessInfo.size(); i++) {
            if(runningAppProcessInfo.get(i).processName.equals("com.example.apprestart")) {
                android.os.Process.killProcess(runningAppProcessInfo.get(i).pid);
                break;
            }
        }

        //restart after 3 seconds
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        launchApp(this, "com.example.apprestart");
        stopSelf();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void launchApp(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        Intent i = manager.getLaunchIntentForPackage(packageName);
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    }
}

3. For demonstration, let’s trigger the app restart service when a button is clicked. Add this button view in MainActivity’s layout file or other activity’s layout you have.

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Restart"
    android:onClick="restartApp"/>

4. Add this method in the MainActivity class or other class you have. Note the method name has to match with the onclick string value in the Button view above.

public void restartApp(View v) {
    Intent mServiceIntent = new Intent(this, RestartService.class);
    startService(mServiceIntent);
}

5. Run the app, hit the restart button, the app will closes and then restart in 3 seconds.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search