Android的Service相关

来源:互联网 发布:人文社会科学类软件 编辑:程序博客网 时间:2024/05/29 02:31

首先在使用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;
}


0 0