android - peekService 返回 null,即使 startService 不返回

标签 android broadcastreceiver

我正在尝试使用来自 BroadcastReceiver 的 Android ServiceService 位于与 BroadcastReceiver 不同的应用程序中。我的理解是,执行此操作的正确方法是首先调用 Context#startService,然后调用 BroadcastReceiver#peekService。对 startService 的调用似乎工作正常,因为它返回了预期的 ComponentName。但是,当我调用 peekService 时,返回了 null。对我做错了什么有什么想法吗?

谢谢!这是包含相关部分的代码 list 。

// The Service in question is com.tingley.myapp.MyService
// Note that this Receiver is in a different application
package com.tingley.myotherapp;

public class MyReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    // Start the Service
    Intent serviceIntent = new Intent();
    serviceIntent.setClassName("com.tingley.myapp", "com.tingley.myapp.MyService");
    ComponentName componentNameOfStartedService = context.startService(serviceIntent);
    Log.d("", "Started service name: " + componentNameOfStartedService);

    // Get an IBinder to the Service
    IBinder serviceBinder = peekService(context, serviceIntent);
    Log.d("", "Got binder from peeking service: " + serviceBinder);
  }
}

Log 语句打印以下内容:

Started service name: ComponentInfo{com.tingley.myapp/com.tingley.myapp.MyService}
Got binder from peeking service: null

最佳答案

peekService() 的文档没有完整描述获得IBinder所需的条件。正如 Dianne Hackborn(Google Android 工程师)在 this post 中解释的那样:“调用 startService() 是不够的——您需要为相同的 Intent 调用 bindService(),因此系统已检索到 IBinder ”。

关于android - peekService 返回 null,即使 startService 不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612646/

相关文章:

android - Android Studio 更新后变量不能包含 $

java - 进一步排序一个已经排序的列表

android - AlarmManager 在模拟器中触发但不在物理设备上触发

android - 运行时异常-无法启动接收器

java - Android 使用 SimpleDateFormat 将字符串解析为日期

Android - ICS 4.0 中的 MediaPlayer 缓冲区大小

android - 使用 Processing 和 Opencv 进行 android 开发?

android - 为什么发送短信时会出现 "Generic Failure"错误?

java - 如何处理网络状态变化时的在线媒体播放器(网络在 WiFi 或移动数据之间切换)?

android - Android 上允许的最大服务和接收器数量