android 安卓 停止指定的Service

private void stopService(String packString, String classString) {//packString classString  传进来的包名和类名

		

		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

		List<ActivityManager.RunningServiceInfo> runServiceList = mActivityManager

				.getRunningServices(20);//得到二十个正在运行的Service放到list中

		for (ActivityManager.RunningServiceInfo runServiceInfo : runServiceList) {

			ComponentName serviceCMP = runServiceInfo.service;

			String serviceName = serviceCMP.getShortClassName(); // service 的类名

			String pkgName = serviceCMP.getPackageName(); // 包名

			System.out.println("比较前:" + serviceName + "-------" + classString);

			System.out.println("比较前:" + pkgName + "-------" + packString);

			if (serviceName.equals(classString) && pkgName.equals(packString)) {

				System.out.println("比较后:" + serviceName + "-------" + classString);

				System.out.println("比较后:" + pkgName + "-------" + packString);

				Intent intent = new Intent();

				intent.setComponent(serviceCMP);

				stopService(intent);

			}

		}

	}

根据你需要停止的Service 传入 包名和类名即可。


2.停止指定包下的Service
private void stopService(String packageName){

			ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

			List<ActivityManager.RunningServiceInfo> list = activityManager.getRunningServices(20);

			for (ActivityManager.RunningServiceInfo serviceInfo : list) {

				if (serviceInfo.service.getPackageName().equals(packageName)) {

					Intent intent = new Intent();

					intent.setComponent(serviceInfo.service);

					stopService(intent);

				}

			}

		}

 

 

你可能感兴趣的:(android)