我的一个应用程序有一个小问题。它使用 aBroadCastReceiver
来检测呼叫何时完成,然后执行一些次要的内务处理任务。这些必须延迟几秒钟,以允许用户查看一些数据并确保通话记录已更新。我目前正在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% 的情况下,通知不会被删除。我怀疑,线程在消息队列处理消息/可运行之前死亡。
我现在正在考虑替代方案postDelayed()
,我的选择之一显然是 AlarmManager。但是,我不确定性能影响(或它使用的资源)。
也许有更好的方法来确保在线程死亡之前处理完所有消息,或者有另一种方法来延迟这两位代码的执行。
谢谢