首页 > 移动平台 > 详细

Android高手之路之获取正在运行的service,以及判断某个service是否正在运行

时间:2015-02-03 19:35:34      阅读:317      评论:0      收藏:0      [点我收藏+]

注:本文改自http://blog.csdn.net/android_tutor/article/details/5824581

其实主要是用了activityManager的getRunningServices来获取正在运行的service的列表。然后用正在运行的服务的名称去比对相等。

看代码:

package com.example.runningservice;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.os.Bundle;
import android.widget.TextView;

public class RunningService extends Activity{
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		TextView mTextView = new TextView(this);
		ActivityManager mActivityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> mServiceList = mActivityManager.getRunningServices(30);
		// the service name which u want to judge
		final String musicClassName = "com.android.launcher2.MusicService"; 
		boolean b = MusicServiceIsStart(mServiceList, musicClassName);  
		mTextView.setText("the service u need to judge is:"+b+"\n"+"all is:"+getServiceClassName(mServiceList));
		setContentView(mTextView);
	}
	
	//judge the service is start
	private boolean MusicServiceIsStart(List<ActivityManager.RunningServiceInfo> mServiceList,String className){
		for(int i=0;i<mServiceList.size();++i){
			if(className.equals(mServiceList.get(i).service.getClassName())){
				return true;
			}
		}
		return false;
	}
	
	// get all service name of list
	private String getServiceClassName(List<ActivityManager.RunningServiceInfo> mServiceList){
		String res = "";
		for(int i=0;i<mServiceList.size();++i){
			res +=mServiceList.get(i).service.getClassName()+"\n";
		}
		return res;
	}
	
	
	
	
}

效果:

技术分享

Android高手之路之获取正在运行的service,以及判断某个service是否正在运行

原文:http://blog.csdn.net/howlaa/article/details/43452255

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!