Atu*_*waj 37 service android android-service
在点击按钮我想用方法来启动服务startService(new Intent(currentActivity.this,MyService.class))
,但如果服务正在运行,我不想把这种方法做,以避免运行服务,已经running.How这possible.I是同时使用意向的服务和服务在同一项目并希望为两者应用相同的条件.
Ion*_*ers 76
服务只运行一次,因此您可以startService(Intent)
多次呼叫.
您将收到onStartCommand()
服务.所以记住这一点.
来源:请注意,多次调用Context.startService()
不会嵌套(尽管它们会导致多次相应的调用onStartCommand()
),因此无论启动多少次,服务都会被停止一次Context.stopService()
或被stopSelf()
调用; 但是,服务可以使用它们的stopSelf(int)
方法来确保在处理启动的意图之前不停止服务.
在:http://developer.android.com/reference/android/app/Service.html主题:服务生命周期
Thi*_*men 20
使用startService()
.启动服务将调用onStartCommand()
如果服务尚未启动它将调用onCreate()
.初始化变量和/或启动一个Thread onCreate()
.
绑定你的服务; 开始通话时:
Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);
Run Code Online (Sandbox Code Playgroud)
然后检查您的服务是否正常工作,使用如下方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
每当我们从任何 Activity 启动任何服务时,Android 系统都会调用该服务的 onStartCommand() 方法,如果该服务尚未运行,系统首先调用 onCreate(),然后调用 onStartCommand()。
也就是说,android 服务在其生命周期中只启动一次,并保持运行直到停止。如果任何其他客户端想要再次启动它,则只会一直调用 onStartCommand() 方法。
归档时间: |
|
查看次数: |
34821 次 |
最近记录: |