首先在使用Service的时候,需要在manifast里配置
<service android:name="com.clarkt.Service.NotifyService"
android:exported="false">
<intent-filter>
<action android:name="com.clarkt.Service.NotifyService"/>
</intent-filter>
</service>
然后就可以在Activity里使用startService(new Intent("com.clarkt.Service.NotifySerice"))启动服务了。
这里要说明一点的就是,无论调用多少次startService,service只会被Create一次,所以其实根本就不用担心service被重复创建
当service已经存在,那么startServcie会调用service的onStart方法
同时如果没有采取stopService停止该service时,即使程序使用system.exit(0)方式退出,仍然会在后台自动创建
即 onCreate->onStart
****
我其实不太明白bindService跟使用Thread有嘛区别,所以一般都是用的startService,这样还方便呵呵
****
判断Service是否运行的方法
/*既然不担心service被重复创建,所以其实这个判断service是否运行的方法基本就没用了= =!*/
public static boolean IsNotifyServiceRunning(Context mcontext,String servName){
ActivityManager activityManager = (ActivityManager)
mcontext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(30);
if (!(serviceList.size()>0)) {
return false;
}
for (int i=0; i<serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(servName) == true) {
Log.i(TAG,"the service is running");
return true;
}
}
Log.d(TAG,"the service does not run yet");
return false;
}
本文详细介绍了如何在Android中配置及使用Service,包括在manifest文件中注册Service、通过Intent启动Service的过程,以及Service生命周期的重要概念。此外,还提供了一个判断Service是否正在运行的方法。
2613

被折叠的 条评论
为什么被折叠?



