Service can be stopped from any running class provided you should have the context.
From the following steps you can stop the running service at specific time using Receiver.
1. Create a WakefulBroadcastReceiver class in your application. On receive action check if service is running or not,if running stop using Context.
public class TestReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase("STOP_TEST_SERVICE")) {
if (isMyServiceRunning(context, TestService.class)) {
Toast.makeText(context,"Service is running!! Stopping...",Toast.LENGTH_LONG).show();
context.stopService(new Intent(context, TestService.class));
}
else {
Toast.makeText(context,"Service not running",Toast.LENGTH_LONG).show();
}
}
}
private boolean isMyServiceRunning(Context context,Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
2. Register the receiver in AndroidManifest.
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="STOP_TEST_SERVICE" />
<action android:name="START_TEST_SERVICE" />
</intent-filter>
</receiver>
3.Create a PendingIntent with desired action, then set scheduled action using AlarmManager in your activity class.
public void setStopServiceAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent().setAction("STOP_TEST_SERVICE"), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
Hope this helps!!