【问题标题】:Android Oreo: Broadcast receiver does not work when application is not in memoryAndroid Oreo:当应用程序不在内存中时,广播接收器不起作用
【发布时间】:2018-01-15 09:35:18
【问题描述】:

我有一个要求,我需要在一周的特定时间向用户显示通知。

我尝试使用警报管理器来实现这一点。

我面临的问题是,当应用程序在内存中时,我的广播侦听器的 onRecieve() 方法工作正常,但如果我终止应用程序(注意:不是强制停止,我只是从内存中删除应用程序) , onRecieve 方法不会被调用。

我可以从 logcat 中看到 alarmManager 正在发送正确的意图,但我的应用程序似乎由于某种原因没有启动。

我已经梳理了所有可能的资源,但似乎都没有解决我的问题。

我的清单:

权限:

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

清单中的意图接收器:

     <receiver android:name=".Alarm">
             <intent-filter>
                 <action android:name="android.intent.action.NOTIFY" />
                 <action android:name="com.myApp.myCustomThing" />
             </intent-filter>
     </receiver>

我的广播接收器:

public class Alarm extends BroadcastReceiver
{
    Context context;
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.i("Info","Inside OnReceive");
        this.context = context;
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        Log.i("Info","Alarm called - showing toast");
        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        Log.i("Info","Trying to create notification");

        wl.release();
    }

    public void setAlarm(Context context)
    {
        Log.i("Info","In Set Alarm");
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        i.setAction("com.myApp.myCustomThing");
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
//        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, pi); // Millisec * Second * Minute
        am.set(AlarmManager.RTC_WAKEUP,1000*60,pi);
        Log.i("Info","Alarm Set");
    }

}

我在 logcat 中看到以下条目,无论应用程序是否在内存中,都会显示日志消息。

 01-15 14:08:06.967 1396-1673/? V/AlarmManager: Triggering alarm #0: 2
 when =60399531 package =notification.me.com.myApp operation
 =*walarm*:com.myApp.myCustomThing flags =0x5

【问题讨论】:

  • 你从哪里打电话给setAlarm()
  • 警报 a = new Alarm(); a.setAlarm(getApplicationContext());来自我的主要活动
  • 你设置了一个闹钟,它会在 60 秒后启动。你确定你等了足够长的时间才能看到这种情况发生吗?
  • 你在什么设备上测试?
  • @大卫一加 5

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


【解决方案1】:

您已在清单文件中明确禁用广播接收器,我无法看到您从哪里启用它,这意味着它永远不会接收任何广播。

从清单文件中删除 android:enabled="false"

【讨论】:

  • 感谢您的回答,但在这种情况下,删除标志似乎没有任何区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多