【问题标题】:BroadcastReceiver not being triggered when app is closed关闭应用程序时未触发广播接收器
【发布时间】:2020-03-15 02:44:13
【问题描述】:

我正在努力让我的应用每天早上 6 点运行一次代码。当应用程序打开并在前台时,这工作得很好,但如果通过滑动关闭应用程序,则永远不会在适当的时间调用代码。

AlarmReceiver.java(出于测试目的,我只是尝试显示一个 Toast 以验证它是否运行)

public class AlarmReceiver extends BroadcastReceiver {

    public static final String intentAction = "com.mpagliaro98.action.NOTIFICATIONS";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(intentAction)) {
            Toast.makeText(context, "RECEIVER CALLED", Toast.LENGTH_LONG).show();
        }
    }
}

MainActivity.java(设置闹钟的地方)

public class MainActivity extends AppCompatActivity {

    ...

    private void setRecurringAlarm() {
        // Set this to run at 6am
        Calendar updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getDefault());
        updateTime.set(Calendar.HOUR_OF_DAY, 6);
        updateTime.set(Calendar.MINUTE, 0);
        updateTime.set(Calendar.SECOND, 0);
        updateTime.set(Calendar.MILLISECOND, 0);

        // Build the pending intent and set the alarm
        Intent i = new Intent(AlarmReceiver.intentAction);
        PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(),
                0, i, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        assert am != null;
        am.setRepeating(AlarmManager.RTC, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
    }
}

AndroidManifest.xml(仅相关部分)

<uses-permission android:name="android.permission.SET_ALARM" />

<receiver
    android:name=".AlarmReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.mpagliaro98.action.NOTIFICATIONS" />
    </intent-filter>
</receiver>

我已经在本网站和其他地方阅读了数十个与此类似的问题,我非常不知道为什么这不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: android notifications broadcastreceiver alarmmanager


    【解决方案1】:

    尝试将接收器更改为

    <receiver android:process=":remote" android:name="AlarmReceiver"></receiver>
    

    Should I use android: process =":remote" in my receiver?

    【讨论】:

    • 我已经添加了它,但不幸的是它并没有产生任何影响。事实上,今天在打开应用程序时调用接收器确实不一致;我试图通过将警报之间的间隔设置为一分钟来对其进行测试,但现在即使应用程序打开,它也只会触发四分之一的时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多