启动service时有两种方法:startService;bindService。
/*
* 判断服务是否启动,context上下文对象 ,className服务的name
*/
public static boolean isServiceRunning(Context mContext, String className) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(30);
if (!(serviceList.size() > 0)) {
return false;
}
Log.e("OnlineService:",className);
for (int i = 0; i < serviceList.size(); i++) {
Log.e("serviceName:",serviceList.get(i).service.getClassName());
if (serviceList.get(i).service.getClassName().contains(className) == true) {
isRunning = true;
break;
}
}
return isRunning;
}
那么如何停止一个service呢?
stopService()和stopSelf()都可以停止通过startService()方式启动的service。
stopService需要传递startService(Intent service)时的intent对象作为参数,停止此intent对应的service。
stopSelf直接停止本service,不需要参数,在service中直接调用即可。
service退出时会调用onDestroy()函数,可以在此函数中进行释放等操作。例如执行MediaPlayer对象的release()并赋值为null,调用System.exit(0);退出应用程序等。
本文介绍了在Android中启动和停止Service的两种主要方法:startService和bindService,并提供了判断Service是否正在运行的方法及如何使用stopService和stopSelf来终止Service。
581

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



