There is a lot of Answers like this answer https://stackoverflow.com/a/19856367/7742857, But still i didn't get the solution i wanted.
The is the Manifest file
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service android:name=".MyService" />
<receiver
android:name=".RestartService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
This is Service class, I'm not using onStartCommand();
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
assert alarmService != null;
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
Log.e("Service_Auto_Restart", "ON");
}
This class is inside Service class
class TimeDisplayTimerTask extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
Timer();
}
});
}
}
and this is is BroadCast Class
public class RestartService extends BroadcastReceiver {
MyService myService;
MyService.TimeDisplayTimerTask timeDisplayTimerTask;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
context.startService(new Intent(context,MyService.class));
myService.getPackagesList("package_names");
myService.getTimer("SELECTED_TIME");
myService.Timer();
timeDisplayTimerTask.run();
Toast.makeText(context,"Restarted",Toast.LENGTH_LONG).show();
}
}
}
I would be grateful for any help you are able to provide.