handler.postDelayed vs. AlarmManager vs

我的一个应用程序中有一个小问题。它使用
BroadCastReceiver
来检测呼叫何时结束,然后执行一些小的内务处理任务。这些必须延迟几秒钟,以允许用户查看一些数据并确保呼叫日志已更新。我目前正在使用
handler.postDelayed()
public class CallEndReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
    if (DebugFlags.LOG_OUTGOING)
        Log.v("CallState changed "
                + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
    if (intent.getStringExtra(TelephonyManager.EXTRA_STATE)
            .equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) {
        SharedPreferences prefs = Utils.getPreferences(context);
        if (prefs.getBoolean("auto_cancel_notification", true)) {
            if (DebugFlags.LOG_OUTGOING)
                Log.v("Posting Handler to remove Notification ");
            final Handler mHandler = new Handler();
             final Runnable mCancelNotification = new Runnable() {
                   public void run() {
                        NotificationManager notificationMgr = (NotificationManager) context
                        .getSystemService(Service.NOTIFICATION_SERVICE);
                notificationMgr.cancel(12443);
                if (DebugFlags.LOG_OUTGOING)
                    Log.v("Removing Notification ");
                   }
                };
                mHandler.postDelayed(mCancelNotification, 4000);


        }
        final Handler updateHandler = new Handler();
         final Runnable mUpdate = new Runnable() {
               public void run() {
        if (DebugFlags.LOG_OUTGOING)
            Log.v("Starting updateService");
        Intent newBackgroundService = new Intent(context,
                CallLogUpdateService.class);
        context.startService(newBackgroundService);
               }
               };
               updateHandler.postDelayed(mUpdate, 5000);

        if (DebugFlags.TRACE_OUTGOING)
            Debug.stopMethodTracing();
        try
        {
        // Stopping old Service
        Intent backgroundService = new Intent(context,
                NetworkCheckService.class);
        context.stopService(backgroundService);
        context.unregisterReceiver(this);
        }
        catch(Exception e)
        {
            Log.e("Fehler beim Entfernen des Receivers", e);
        }
    }

}
} 现在我遇到了这个问题,这种设置大约有90%的时间都可以使用。在大约10%的情况下,通知不会被删除。我怀疑,线程在消息队列处理消息/ runnable之前就已经死了。 我现在正在考虑
postDelayed()
的替代品,我的一个选择显然是AlarmManager。但是,我不确定性能影响(或它使用的资源)。 也许有更好的方法可以确保在线程死亡之前处理所有消息或者延迟执行这两位代码的其他方法。 谢谢     
已邀请:
  我目前正在使用handler.postDelayed()来实现此目的: 这不是一个好主意,假设清单中的过滤器触发了
BroadcastReceiver
。   现在我遇到了这个问题,这种设置大约有90%的时间都可以使用。在大约10%的情况下,通知不会被删除。我怀疑,线程在消息队列处理消息/ runnable之前就已经死了。 更准确地说,该过程终止,随身携带。   我现在正在考虑postDelayed()的替代方案,我的一个选择显然是AlarmManager。但是,我不确定性能影响(或它使用的资源)。 没那么糟糕。另一种可能性是在
IntentService
中进行延迟工作 - 通过调用
startService()
触发 - 并使其在后台线程中休眠几秒钟。     
让我们尝试一种新方法。使用RxJava。如果您希望同时,顺序地运行数百个此类延迟任务,与异步任务结合,使用同步链接异步调用链接等,那么原型和更容易管理大量线程要简单得多。 首先,设置订阅者。请记住
Subscriber
Subscriber
上应该只进行一次以避免内存泄漏。
// Set up a subscriber once
private Subscuber<Long> delaySubscriber = new Subscuber<Long> () {
    @Override
    public void onCompleted() {
        //Wrap up things as onCompleted is called once onNext() is over
    }
    @Override
    public void onError(Throwable e) {
        //Keep an eye open for this. If onCompleted is not called, it means onError has been called. Make sure to override this method
    }
    @Override
    public void onNext(Long aLong) {
        // aLong will be from 0 to 1000
        // Yuor code logic goes here

        // If you want to run this code just once, just add a counter and call onComplete when the counter runs the first time

    }
} 
下面的代码段只会在订阅者的onNext()中发出
1
。 请注意,这是在由RxJava库创建和管理的Computation Threadpool上完成的。
//Now when you want to start running your piece of cade, define an Observable interval that'll emit every second
private Observable<Long> runThisAfterDelay = Observable.just(1).delay(1000, TimeUnit.MILLISECONDS, Schedulers.computation());
// Subscribe to begin the emissions.
runThisAfterDelay.subscribe(delaySubscriber);
如果你想在每一秒之后运行一个代码,比如说,你可以这样做:
private Observable<Long> runThisOnInterval = Observable.interval(1000, TimeUnit.MILLISECONDS, Schedulers.computation());
    
除了第一个答案之外,您可能还想考虑API文档对
onReceive
方法的说法:   [...]该函数通常在其进程的主线程中调用,因此您永远不应该在其中执行长时间运行的操作[...] 所以看起来一般来说,开始在
onReceive
内等待几次的东西并不是一个好主意(即使在你的情况下,它低于10s的限制)。 我对BroadcastReceiver有类似的timinig问题。我无法处理我的结果,即使我已经被调用了我正在考虑的内容。似乎
BroadastReceiver
正在运行的线程在我的结果处理完成之前被杀死了。我的解决方案是启动一个新线程来执行所有处理。     
AlarmManager似乎在短时间内(例如10秒)不能很好地工作,并且根据用户报告,行为在很大程度上取决于固件。 最后我决定在我的服务中使用
Handler
Runnable
。 创建
Handler
时,一定要在Service类中创建它,而不是在BroadcastReceiver中创建它,因为在最后一种情况下你会得到
Can't create Handler inside thread that has not called Looper.prepare()
public class NLService extends NotificationListenerService {
    private NLServiceReceiver nlservicereciver;
    Handler delayUpdateHandler = new Handler();
    private Runnable runBroadcastUpdate;

    public void triggerViewUpdate() {
        /* Accumulate view updates for faster, resource saving operation.
        Delay the update by some milliseconds.
        And if there was pending update, remove it and plan new update.
         */
        if (runBroadcastUpdate != null) {
            delayUpdateHandler.removeCallbacks(runBroadcastUpdate);
        }
        runBroadcastUpdate = new Runnable() {
            public void run() {
                // Do the work here; execution is delayed
            }
        };
        delayUpdateHandler.postDelayed(runBroadcastUpdate, 300);
    }

    class NLServiceReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            triggerViewUpdate();
        }
    }

}
    

要回复问题请先登录注册