一个服务只会运行一次,因此您可以多次调用startService(Intent)
。
您将在服务中收到onStartCommand()
。请记住这一点。
来源:
请注意,多次调用Context.startService()
不会嵌套(虽然它们会导致多个相应的onStartCommand()
调用),因此无论启动多少次服务,一旦调用Context.stopService()
或stopSelf()
,服务将停止;但是,服务可以使用它们的stopSelf(int)
方法,以确保在处理启动意图之前不会停止服务。
来自:http://developer.android.com/reference/android/app/Service.html 话题:Service Lifecycle
startService()
始终会触发 onStartCommand()
。因此,要么不调用 startService()
,要么编写一个更加智能的 onStartCommand()
函数以应对多次调用。 - CommonsWare使用startService()
。
启动服务将调用onStartCommand()
,如果服务尚未启动,则会调用onCreate()
。在onCreate()
中初始化变量和/或启动线程。
绑定您的服务; 在启动时调用:
Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);
然后检查你的服务是否在工作状态中,可以使用以下类似的方法:
public static boolean isServiceRunning(String serviceClassName){
final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
return true;
}
}
return false;
}
因此,为了避免一遍又一遍地重新启动任务,您可以使用布尔值来表示任务已经开始或正在进行。将该方法放置在oncreate和onstartCommand中,并使用布尔值进行检查:
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;
}