Android 两个Service的相互监视实现代码

两个Service之间相互监视的实现

在实际开发中可能需要用到两个Service相互监视的情况,本示例就是实现此功能以作参考。

服务A:

public class ServiceA extends Service {

  private static final String TAG = ServiceA.class.getSimpleName();
  MyBinder mBinder;
  MyServiceConnection mServiceConnection;
  PendingIntent mPendingIntent;

  @Override
  public void onCreate() {
    super.onCreate();

    if(mBinder==null)
    {
      mBinder=new MyBinder();
    }
    mServiceConnection=new MyServiceConnection();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    ServiceA.this.bindService(new Intent(ServiceA.this,ServiceB.class),mServiceConnection, Context.BIND_IMPORTANT);
    mPendingIntent=PendingIntent.getService(this,0,intent,0);
    Notification.Builder builder=new Notification.Builder(this);
    builder.setTicker("守护服务A启动中")
        .setContentText("我是来守护服务B的")
        .setContentTitle("守护服务A")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(mPendingIntent)
        .setWhen(System.currentTimeMillis());
    Notification notification=builder.build();

    startForeground(startId,notification);

    return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
    return mBinder;
  }

  public class MyBinder extends IBridgeInterface.Stub {

    @Override
    public String getName() throws RemoteException {
      return "name:"+TAG;
    }
  }

  class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
      String name=null;
      try {
        name= IBridgeInterface.Stub.asInterface(iBinder).getName();
      } catch (RemoteException e) {
        e.printStackTrace();
      }

      Toast.makeText(ServiceA.this,name+"连接成功",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
      Toast.makeText(ServiceA.this,TAG+"断开连接",Toast.LENGTH_SHORT).show();

      ServiceA.this.startService(new Intent(ServiceA.this,ServiceB.class));

      ServiceA.this.bindService(new Intent(ServiceA.this,ServiceB.class),mServiceConnection, Context.BIND_IMPORTANT);

    }
  }

}

服务B:

public class ServiceB extends Service {

  private static final String TAG = ServiceB.class.getSimpleName();
  private PendingIntent mPendingIntent;
  private MyBinder mBinder;
  private MyServiceConnection mServiceConnection;

  @Override
  public IBinder onBind(Intent intent) {
    return mBinder;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    if (mBinder == null) {
      mBinder = new MyBinder();
    }

    mServiceConnection = new MyServiceConnection();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    this.bindService(new Intent(ServiceB.this, ServiceA.class), mServiceConnection, Context.BIND_IMPORTANT);
    mPendingIntent = PendingIntent.getService(this, 0, intent, 0);
    Notification.Builder builder = new Notification.Builder(this);

    builder.setTicker("守护服务B启动中")
        .setContentText("我是来守护服务A的")
        .setContentTitle("守护服务B")
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentIntent(mPendingIntent)
        .setWhen(System.currentTimeMillis());
    Notification notification = builder.build();
    startForeground(startId, notification);

    return START_STICKY;
  }

  public class MyBinder extends IBridgeInterface.Stub {

    @Override
    public String getName() throws RemoteException {
      return "name:"+TAG;
    }
  }

  class MyServiceConnection implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
      String name=null;
      try {
        name=IBridgeInterface.Stub.asInterface(iBinder).getName();
      } catch (RemoteException e) {
        e.printStackTrace();
      }
      Toast.makeText(ServiceB.this, name + "连接成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
      Toast.makeText(ServiceB.this, TAG + "断开连接", Toast.LENGTH_SHORT).show();

      ServiceB.this.startService(new Intent(ServiceB.this, ServiceA.class));
      ServiceB.this.bindService(new Intent(ServiceB.this, ServiceA.class), mServiceConnection, Context.BIND_IMPORTANT);
    }
  }

}

IBridgeInterface.aidl

1 interface IBridgeInterface {
2   String getName();
3 }

界面:

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, ServiceA.class));
    startService(new Intent(this, ServiceB.class));
  }

}

AndroidManifest.xml

<service android:name=".services.ServiceA" />
    <service
      android:name=".services.ServiceB"
       android:process=":remote" />

由于涉及到跨进程,onServiceConnected() 方法中使用

IBridgeInterface.Stub.asInterface(iBinder).getName();
而不能直接类型转换

((ServiceA.MyBinder)iBinder).getName();

onStartCommand

onStartCommand() 方法必须返回整型数。整型数是一个值,用于描述系统应该如何在服务终止的情况下继续运行服务。

返回的值必须是以下常量之一:

START_NOT_STICKY

  如果系统在 onStartCommand() 返回后终止服务,则除非有挂起 Intent 要传递,否则系统不会重建服务。

START_STICKY

  如果系统在 onStartCommand() 返回后终止服务,则会重建服务并调用 onStartCommand(),但绝对不会重新传递最后一个 Intent。相反,除非有挂起 Intent 要启动服务(在这种情况下,将传递这些 Intent ),否则系统会通过空 Intent 调用 onStartCommand()。这适用于不执行命令、但无限期运行并等待作业的媒体播放器(或类似服务)。

START_REDELIVER_INTENT

  如果系统在 onStartCommand() 返回后终止服务,则会重建服务,并通过传递给服务的最后一个 Intent 调用 onStartCommand()。任何挂起 Intent 均依次传递。这适用于主动执行应该立即恢复的作业(例如下载文件)的服务。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • Android基于service实现音乐的后台播放功能示例

    本文实例讲述了Android基于service实现音乐的后台播放功能.分享给大家供大家参考,具体如下: Service是一个生命周期长且没有用户界面的程序,当程序在各个activity中切换的时候,我们可以利用service来实现背景音乐的播放,即使当程序退出到后台的时候,音乐依然在播放.下面我们给出具体例子的实现: 当然,首先要在资源文件夹中添加一首MP3歌曲: 要实现音乐的播放,需要在界面中放置两个按钮,用来控制音乐的播放和停止,通过使用startService和stopService来实现

  • Android Service中方法使用详细介绍

     service作为四大组件值得我们的更多的关注 在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务.例如,一个从service播放音乐的音乐播放器,应被设置为前台运行,因为用户会明确地注意它的运行.在状态栏中的通知可能会显示当前的歌曲并且允许用户启动一个activity来与音乐播放器交互. Service的两种实现形式 1.非绑定 通过调用应用程序组件(例如Activity)的startService()方法来启动一个服务.一旦启动,服务就会在

  • Android中Service与Activity之间通信的几种方式

    在Android中,Activity主要负责前台页面的展示,Service主要负责需要长期运行的任务,所以在我们实际开发中,就会常常遇到Activity与Service之间的通信,我们一般在Activity中启动后台Service,通过Intent来启动,Intent中我们可以传递数据给Service,而当我们Service执行某些操作之后想要更新UI线程,我们应该怎么做呢?接下来我就介绍两种方式来实现Service与Activity之间的通信问题 1.通过Binder对象 当Activity通

  • Android实现微信自动向附近的人打招呼(AccessibilityService)

    学习功能强大的AccessibilityService!!! 以下是本人根据自动抢红包的实现思路敲的用于微信自动向附近的人打招呼的核心代码 public class AutoService extends AccessibilityService implements View.OnClickListener { private static final String TAG = "test"; /** * 微信的包名 */ static final String WECHAT_PAC

  • 浅谈Android Activity与Service的交互方式

    实现更新下载进度的功能 1. 通过广播交互 Server端将目前的下载进度,通过广播的方式发送出来,Client端注册此广播的监听器,当获取到该广播后,将广播中当前的下载进度解析出来并更新到界面上. 优缺点分析: 通过广播的方式实现Activity与Service的交互操作简单且容易实现,可以胜任简单级的应用.但缺点也十分明显,发送广播受到系统制约.系统会优先发送系统级广播,在某些特定的情况下,我们自定义的广播可能会延迟.同时在广播接收器中不能处理长耗时操作,否则系统会出现ANR即应用程序无响应

  • Android Activity 与Service进行数据交互详解

    ①从设计的角度来讲: Android的Activity的设计与Web页面非常类似,从页面的跳转通过连接,以及从页面的定位通过URL,从每个页面的独立封装等方面都可以看出来,它主要负责与用户进行交互. Service则是在后台运行,默默地为用户提供功能,进行调度和统筹.如果一棵树的地上部分是Activity的话,它庞大的根须就是Service.Android的服务组件没有运行在独立的进程或线程中,它和其他的组件一样也在应用的主线程中运行,如果服务组件执行比较耗时的操作就会导致主线程阻塞或者假死,从

  • Android Service中使用Toast无法正常显示问题的解决方法

    本文实例讲述了Android Service中使用Toast无法正常显示问题的解决方法.分享给大家供大家参考,具体如下: 在做Service简单练习时,在Service中的OnCreate.OnStart.OnDestroy三个方法中都像在Activity中同样的方法调用了Toast.makeText,并在Acitivy中通过两个按钮来调用该服务的onStart和onDestroy方法: DemoService代码如下: @Override public void onCreate() { su

  • Android Service服务不被停止详解及实现

    Android Service服务一直运行: 最近有个项目需求是后台一直运行Service,但是一般都是可以手动停止的,这里就提供一个方法让Android Service服务一直运行,大家看下. 1.设置->应用->运行中->停止->杀死service 这样可以在service的onDestroy()方法中重启service public void onDestroy() { Intent service = new Intent(this, MyService.class); s

  • Android 如何保证service在后台不被kill

    Android 其实无法做多绝对的不被后台kill掉,我们只能尽量使用一些操作提升不被kill的机会. 一.onStartCommand方法,返回START_STICKY START_STICKY 在运行onStartCommand后service进程被kill后,那将保留在开始状态,但是不保留那些传入的intent.不久后service就会再次尝试重新创建,因为保留在开始状态,在创建     service后将保证调用onstartCommand.如果没有传递任何开始命令给service,那将

  • Android AccessibilityService实现微信抢红包插件

    在你的手机更多设置或者高级设置中,我们会发现有个无障碍的功能,很多人不知道这个功能具体是干嘛的,其实这个功能是为了增强用户界面以帮助残障人士,或者可能暂时无法与设备充分交互的人们 它的具体实现是通过AccessibilityService服务运行在后台中,通过AccessibilityEvent接收指定事件的回调.这样的事件表示用户在界面中的一些状态转换,例如:焦点改变了,一个按钮被点击,等等.这样的服务可以选择请求活动窗口的内容的能力.简单的说AccessibilityService就是一个后

随机推荐