I want to close Whatsapp
, if it is every opened by the user. By close, I mean to completely kill it from the background. The service class should be able to run for 30 seconds. My code is as follows:
serviceclass_code:
public class Timer extends Service {
long time=30000; //30 seconds
Notification n;
long current_time=0;
String app="Whatsapp";
public Timer() {
}
@Override
public void onCreate() {
current_time=System.currentTimeMillis();
n = new NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("Timer")
.setContentText("You can use "+app+" only for "+time+" seconds")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build();
startForeground(1,n);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.killBackgroundProcesses("com.whatsapp"); //package name of 'Whatsapp`
if((System.currentTimeMillis() - current_time)==time){
stopForeground(Service.STOP_FOREGROUND_REMOVE); //should remove notification
stopSelf(); //should stop service
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
But when I execute the code, neither does the service class kill the Whatsapp
process, nor does the notification get dismissed after 30 seconds is over. The service keeps on running forever, and Whatsapp
is still running in the background. Why?