【问题标题】:WakefulBroadcastReceiver in support library vs cwac-wakeful by commonsware支持库中的 WakefulBroadcastReceiver 与 commonsware 的 cwac-wakeful
【发布时间】:2015-01-04 08:29:31
【问题描述】:

我正在使用 commonsware WakefulIntentService 来做清醒的工作。 使用支持库中的commonsware library 而不是WakefulBroadcastReceiver 有什么优势吗?

这是我使用支持库的代码

import android.support.v4.content.WakefulBroadcastReceiver;    

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

public class SimpleWakefulService extends IntentService {
    public SimpleWakefulService() {
        super("SimpleWakefulService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }
}

This 是文档。

  1. 它们之间有什么区别?
  2. 我应该在哪里使用 commonsware 库而不是支持 图书馆?

【问题讨论】:

  • 他们解决了同样的基本问题。 WakefulBroadcastReceiver 至少在理论上可以与普通的Service 一起使用(小心!),因此它更加灵活。它也是 Android 支持包的一部分,您可能已经将其用于其他内容,因此它为您节省了依赖项。 OTOH,在 2008 年 4 月至 2013 年 8 月期间,WakefulBroadcastReceiver 不存在,因此WakefulIntentService 是主要选项。
  • @CommonsWare ,几个月前我看到你更新了库。目前,你的 lib 是否比 WakefulBroadCastReceiver 更好?
  • @CauCuKien:Rob 的回答很好地总结了差异。除此之外,我不知道您认为“更好”是什么意思。

标签: android broadcastreceiver intentservice commonsware-cwac


【解决方案1】:

它们几乎相同。

支持库的 WakefulBroadcastReceiver 采用部分唤醒锁定,将锁定 ID 作为额外的锁定 ID 放在您应该提供给 IntentServiceIntent 中,完成后您必须调用 completeWakefulIntent ()加工。所以获取和释放是在不同的地方完成的,这有点代码味道。

CommonsWare 的WakefulIntentService 自行获取和释放部分唤醒锁。

如果您同意获取和释放应该在同一个地方完成,您可以将常规的BroadcastReceiverWakefulIntentService 结合使用。

如果您不那么介意并认为使用知名库更重要,这样新开发人员(或一年后的您)不必(重新)学习新东西,然后使用支持库。

更新

另外:在WakefulBroadcastReceiver 的文档中,它警告可能会被中断并丢失唤醒锁。您需要在IntentService 中获取自己的唤醒锁以防止这种情况发生。使用 CommonsWare,您可以依靠它来重新获得锁。

【讨论】:

  • 您提到了被中断和丢失唤醒锁的可能性。但是我在官方文档中找不到它的位置。您能否提供一个链接或示例以再次检测和获取唤醒锁?
  • @CauCuKien,请参阅WakefulBroadcastReceiver 的开发人员文档。有一个示例 SimpleWakefulService 类,其中函数 onHandleIntent(Intent intent) 内部的 cmets 警告这种可能性:“注意,当使用这种方法时......”
猜你喜欢
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
相关资源
最近更新 更多