if(startService(someIntent) != null) {Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();}else {Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();}
/*** Check if the service is Running* @param serviceClass the class of the Service** @return true if the service is running otherwise false*/public boolean checkServiceRunning(Class<?> serviceClass){ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){if (serviceClass.getName().equals(service.service.getClassName())){return true;}}return false;}
public int onStartCommand(Intent intent, int flags, int startId) {
serviceRunning = true;...}
@Overridepublic void onDestroy(){serviceRunning = false;
}
@Overridepublic void onCreate() {LocalBroadcastManager.getInstance(this).registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping"));//do not forget to deregister the receiver when the service is destroyed to avoid//any potential memory leaks}
private class ServiceEchoReceiver extends BroadcastReceiver {public void onReceive (Context context, Intent intent) {LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("pong"));}}
Activity
bool serviceRunning = false;
protected void onCreate (Bundle savedInstanceState){LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong"));LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping"));if(!serviceRunning){//run the service}}
private BroadcastReceiver pong = new BroadcastReceiver(){public void onReceive (Context context, Intent intent) {serviceRunning = true;}}
public class PingableService extends Service {public static final String ACTION_PING = PingableService.class.getName() + ".PING";public static final String ACTION_PONG = PingableService.class.getName() + ".PONG";
public int onStartCommand (Intent intent, int flags, int startId) {LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(ACTION_PING));return super.onStartCommand(intent, flags, startId);}
@Overridepublic void onDestroy () {LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);super.onDestroy();}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive (Context context, Intent intent) {if (intent.getAction().equals(ACTION_PING)) {LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());manager.sendBroadcast(new Intent(ACTION_PONG));}}};}
public class MyActivity extends Activity {private boolean isSvcRunning = false;
@Overrideprotected void onStart() {LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());manager.registerReceiver(mReceiver, new IntentFilter(PingableService.ACTION_PONG));// the service will respond to this broadcast only if it's runningmanager.sendBroadcast(new Intent(PingableService.ACTION_PING));super.onStart();}
@Overrideprotected void onStop() {LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);super.onStop();}
protected BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive (Context context, Intent intent) {// here you receive the response from the serviceif (intent.getAction().equals(PingableService.ACTION_PONG)) {isSvcRunning = true;}}};}
public abstract class Context {
...
/** @return {true} If you have successfully bound to the service,* {false} is returned if the connection is not made* so you will not receive the service object.*/public abstract boolean bindService(@RequiresPermission Intent service,@NonNull ServiceConnection conn, @BindServiceFlags int flags);
int res = ActivityManagerNative.getDefault().bindService(...);return res != 0;
交易通过binder进行:
ServiceManager.getService("activity");
下一篇:
public static IBinder getService(String name) {try {IBinder service = sCache.get(name);if (service != null) {return service;} else {return getIServiceManager().getService(name);
这是通过ActivityThread设置的:
public final void bindApplication(...) {
if (services != null) {// Setup the service cache in the ServiceManagerServiceManager.initServiceCache(services);}
这在ActivityManagerService的方法中调用:
private final boolean attachApplicationLocked(IApplicationThread thread,int pid) {...thread.bindApplication(... , getCommonServicesLocked(),...)
/*** Return the global "context object" of the system. This is usually* an implementation of IServiceManager, which you can use to find* other services.*/public static final native IBinder getContextObject();
/*** Provide a binder to an already-bound service. This method is synchronous* and will not start the target service if it is not present, so it is safe* to call from {@link #onReceive}.** For peekService() to return a non null {@link android.os.IBinder} interface* the service must have published it before. In other words some component* must have called {@link android.content.Context#bindService(Intent, ServiceConnection, int)} on it.** @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)}* @param service Identifies the already-bound service you wish to use. See* {@link android.content.Context#bindService(Intent, ServiceConnection, int)}* for more information.*/public IBinder peekService(Context myContext, Intent service) {IActivityManager am = ActivityManager.getService();IBinder binder = null;try {service.prepareToLeaveProcess(myContext);binder = am.peekService(service, service.resolveTypeIfNeeded(myContext.getContentResolver()), myContext.getOpPackageName());} catch (RemoteException e) {}return binder;}
简而言之:)
"为已绑定的服务提供绑定器。此方法是同步的,如果不存在,则不会启动目标服务。"
public IBinder peekService(意图服务,字符串解析类型,字符串调用Package)抛出远程异常;
public final class AService extends Service {
private static AService mInstance = null;
public static boolean isServiceCreated() {try {// If instance was not cleared but the service was destroyed an Exception will be thrownreturn mInstance != null && mInstance.ping();} catch (NullPointerException e) {// destroyed/not-startedreturn false;}}
/*** Simply returns true. If the service is still active, this method will be accessible.* @return*/private boolean ping() {return true;}
@Overridepublic void onCreate() {mInstance = this;}
@Overridepublic void onDestroy() {mInstance = null;}}
if (isMyServiceRunning(MainActivity.this, xyzService.class)) { // Service class name// Service running} else {// Service Stop}
public static boolean isMyServiceRunning(Activity activity, Class<?> serviceClass) {ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {if (serviceClass.getName().equals(service.service.getClassName())) {return true;}}return false;}
1. Open Settings in your Android device.2. Find Developer Options.3. Find Running Services option.4. Find your app icon.5. You will then see all the service that belongs to your app running in the background.
public class MyMusicService extends Service {
private static MyMusicService instance = null;
public static boolean isMyMusicServiceRunning() {return instance != null;}