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

注:本文改自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;
	}
	
	
	
	
}

效果:

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。