On click of a button I want to start service using method startService(new Intent(currentActivity.this,MyService.class))
but if service is running I don\'t want to
So, for avoiding restarting a task again and again, You can use boolean values, that the task is already started or ongoing. Put the method both in oncreate and onstartCommand, and checked with the boolean:
boolean isTimerTaskRunning = false;
private boolean isServiceKeepRunning(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
return settings.getBoolean("silentModeKeepRunning", true);
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: Called");
Log.i(TAG, "onCreate: keepRunning "+isServiceKeepRunning());
if(!isTimerTaskRunning) {
startTimerTask();
isTimerTaskRunning = true;
}
//startForeground(REQUEST_CODE /* ID of notification */, notificationbuilder().build());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
localData = new LocalData(this);
// return super.onStartCommand(intent, flags, startId);
Log.i(TAG, "onStartCommand: Called");
Log.i(TAG, "onStartCommand: keepRunning "+isServiceKeepRunning());
Toast.makeText(this, "This is The Mode For Silent. ", Toast.LENGTH_LONG).show();
if(!isTimerTaskRunning) {
Log.i(TAG, "TimerTask was not Running - started from onStartCommand");
startTimerTask();
isTimerTaskRunning = true;
}else {
Log.i(TAG, "TimerTask was already Running - checked from onStartCommand");
}
//return START_REDELIVER_INTENT;
startForeground(REQUEST_CODE /* ID of notification */, notificationbuilder().build());
return START_STICKY;
}