如何使用PendingIntent从一个服务进行通信,以在客户端/活动 [英] How to use PendingIntent to communicate from a Service to a client/Activity

查看:129
本文介绍了如何使用PendingIntent从一个服务进行通信,以在客户端/活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读上的Andr​​oid开发者网站下面的文字,根据具体的框架主题 - >服务 - >启动服务(http://developer.android.com/guide/topics/fundamentals/services.html# StartingAService)

I have been reading the following text on the Android Developers Site, specifically under the Framework Topics -> Services -> Starting a Service (http://developer.android.com/guide/topics/fundamentals/services.html#StartingAService)

在那里,它规定了以下内容:

There it states the following :

如果服务不还提供绑定,附带startService()的目的是应用程序组件和服务之间的通信的唯一方式。但是,如果你希望服务的结果发回,然后启动该服务的客户端可以建立用于广播一个PendingIntent(与getBroadcast()),并提供给在启动该服务的意向的服务。然后,服务可以使用广播来提供一个结果。

我有关于这个问题的一个couiple:

I have a couiple of questions regarding this :

1 - ?这是否文本既适用于服务和IntentServices

1 - Does this text both apply to Services AND IntentServices ?

2 - 如何(codewise)应该从服务中实现这一目标:服务就可以用广播来提供结果并也将在这里所提到的广播交付结果原来的客户端/活动?有一些方法应该被覆盖(如onActivityResult())还是什么?

2- How (codewise) should this be achieved from within the Service : The service can then use the broadcast to deliver a result. and also where would the mentioned broadcast deliver the result to the original client/activity ? Is there some method that should be overwritten (like onActivityResult()) or something ?

推荐答案


有人问几个月前,但在任何情况下,仍然在寻找答案,我希望我能有所帮助。


Question was asked few months ago, but in case anyone is still looking for answer I hope I can help.

在下面的例子中,我们有本地服务,负责执行一些耗时的操作。活动使得对服务的请求,但不会绑定到它 - 只要发送一个请求的意图。此外,活动包括了BroadcastReceiver那应该叫回来时,服务的要求完成任务的信息。该信息被传递由PendingIntent。该服务处理在后台线程中的任务,当任务完成后,服务广播与答案的BroadcastReceiver。

In the example below we have local service, responsible for performing some time-consuming operations. Activity makes the requests to the service, but does not bind to it - just sends the intent with request. Additionally, Activity includes the information of BroadcastReceiver that should be called back when service is done with the requested task. The information is passed by PendingIntent. The service handles the task in background thread and when task is finished, service broadcasts the BroadcastReceiver with an answer.

1。创建BroadcastReceiver的子类:

public class DataBroadcastReceiver extends BroadcastReceiver {
   static Logger log = LoggerFactory.getLogger(DataRequestService.class);   
   @Override
   public void onReceive(Context context, Intent intent) {
      log.info(" onReceive");
   }
}

这个广播接收器将通知从服务中,当任务完成。

2。创建服务

This broadcast receiver will be notified from service, when task is done.

2. Create Service

public class DataRequestService extends Service {

   private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
         super(looper);
      }

      @Override
      public void handleMessage(Message msg) {
         log.info("handleMessage");
         //... performing some time-consuming operation         
         Bundle bundle = msg.getData();
         PendingIntent receiver = bundle.getParcelable("receiver");
         // Perform the operation associated with PendingIntent
         try {            
            //you can attach data from the operation in the intent.
            Intent intent = new Intent();
            Bundle b = new Bundle();
            //b.putString("key", value);
            intent.putExtras(b);
            receiver.send(getApplicationContext(), status, intent);
         } catch (CanceledException e) {         
         e.printStackTrace();
         }         
      }
   }

   @Override
   public void onStart(Intent intent, int startId) {
      Bundle bundle = intent.getExtras();
      msg.setData(bundle);
      mServiceHandler.sendMessage(msg);
   }

好了,最重要的部分是的h​​andleMessage()方法。服务只是使广播运营交付成果,以广播接收器。

3。您还需要注册广播接收器,服务于一体的Manifest.xml

Well, the most important part is in handleMessage() method. Service simply makes the broadcasts operation for delivering results to Broadcast Receiver.

3. You also need to register your broadcast receiver and service in Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ramps.servicetest"
    android:versionCode="1"
    android:versionName="1.0" >
   ....
       <service android:name=".service.DataRequestService" android:exported="false"/>
       <receiver android:name=".service.DataBroadcastReceiver"></receiver>
    </application>
</manifest><br>

4。最后,请要求从活动服务:

Intent serviceIntent = new Intent(context, DataRequestService.class);   
   @Override
   public void onClick(View v) {
      //this is the intent that will be broadcasted by service.
      Intent broadcastReceiverIntent = new Intent(context, DataBroadcastReceiver.class);      
      //create pending intent for broadcasting the DataBroadcastReceiver
      PendingIntent pi = PendingIntent.getBroadcast(context, 0, broadcastReceiverIntent, 0);      
      Bundle bundle = new Bundle();            
      bundle.putParcelable("receiver", pi);
      //we want to start our service (for handling our time-consuming operation)
      Intent serviceIntent = new Intent(context, DataRequestService.class);
      serviceIntent.putExtras(bundle);
      context.startService(serviceIntent);
   }



5。发应答原始客户端/活动



5. Delivering response to original client/activity.

您可以从您的所有活动都将延长抽象的活动。这abstrct活动可以自动注册/注销自己作为回应听众在广播接收机。这里就不多的选择实际上,但是,如果你保持静态引用您的活动,那么你必须删除refernece活动时被破坏是非常重要的。照片

You can have abstract activity from which all your activities will be extending. This abstrct activity can automatically register/deregister itself as a response listener in broadcast receiver. Not many options here actually, but it is important that if you keep static references to your activity then you must remove the refernece when activity is destroyed.

问候,
坡道

这篇关于如何使用PendingIntent从一个服务进行通信,以在客户端/活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆