【问题标题】:AlarmManager is discarded when application is cleared from background当应用程序从后台清除时,AlarmManager 被丢弃
【发布时间】:2015-03-04 12:48:14
【问题描述】:

这就是我创建警报的方式。 当应用程序仍在后台运行时,会触发警报。 但是当它从最近的应用程序中清除时,警报就会被丢弃。我正在注册一个新的接收器并提供一个独特的操作来区分两个警报。我的代码有什么错误吗?

        String filter_action = "myPackageName" + request_code_value +"_time";

        IntentFilter filter = new IntentFilter(filter_action);

        registerReceiver(new AlarmReciever(), filter);

        Intent intent = new Intent(filter_action);
        intent.putExtra(getString(R.string.get_current_intent_value), request_code_value);
        intent.putExtra(getString(R.string.alarmtext), alarm_title);
        intent.putExtra(getString(R.string.alarm_time), newAlarm_Choose_Alarm_Value.getText().toString());

        Calendar calNow = Calendar.getInstance();
        Calendar calSet = (Calendar) calNow.clone();


        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, request_code_value, intent, 0);


        calSet.setTimeInMillis(timeInMillis);

        if (calSet.compareTo(calNow) <= 0) {
            // Today Set time passed, count to tomorrow
            calSet.add(Calendar.DATE, 1);
        }

        alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);

清单文件。

<receiver android:name="com.bigbangpartners.YoWakeUp.activities.AlarmReciever" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="AlarmManager_Start" />
        </intent-filter>
</receiver>

请帮助我。 提前致谢。

【问题讨论】:

    标签: android broadcastreceiver alarmmanager android-pendingintent android-broadcast


    【解决方案1】:

    如果您以编程方式在您的Activitys 中注册和取消注册BroadcastReceiver,那么以这种方式创建的BroadcastReceiver 将仅在应用进程处于活动状态时保持存在。因此,当您从最近使用的应用列表中删除您的应用时,BroadcastReceiver 实际上也会被销毁。

    另一方面,在清单中注册的BroadcastReceiver 是一个全局的、永久的 Android 应用程序组件,无论应用程序进程是否存在,它都会永远存在。

    如果您希望即使应用程序不在前台也能激活警报,那么您需要在应用程序清单中注册BroadcastReceiver 并指定警报操作。你没有那样做,我相信这是你问题的根源。

    你应该做什么:

    1. 在清单中定义您的BroadcastReceiver,如下所示:

    <receiver android:name="com.bigbangpartners.YoWakeUp.activities.AlarmReciever" >        
    </receiver>
    

    2. 删除应用代码中对registerReceiver()unRegisterReceiver() 的所有调用,因为这不是必需的。

    3. 像这样定义你的闹钟Intent

    Intent intent = new Intent(this, AlarmReceiver.class);
    

    其余代码保持不变。首先尝试一下,看看它是否有效。

    【讨论】:

    • 如何使用我在清单中注册的广播接收器。你能告诉我如何根据上面的代码为它设置操作吗?
    • 首先我需要理解你所说的“提供一个独特的动作来区分两个警报”是什么意思......这就是你以编程方式注册接收器的原因,我明白......但是为什么你需要“区分两个警报”?
    • 因为我正在创建一个应用程序,用户可以在其中创建任意数量的警报。所以我想我需要区分用户创建的警报。我在想,对于多个警报,需要有不同的操作,以免被覆盖。
    • hmm ....首先让我们解决即使应用程序消失也触发警报的问题...查看编辑的答案
    • 到目前为止你到达了什么地方?
    猜你喜欢
    • 2012-05-02
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多