简体   繁体   English

应用程序从后台删除时,广播接收器无法正常工作?

[英]Broadcast Receiver is not working when application is removed from background?

I am trying to run this code in my mobile app, but it is not running and also giving no error. 我试图在我的移动应用程序中运行此代码,但它没有运行,也没有给出任何错误。 I have tried printing log also, but it is not showing anything in logcat. 我也试过打印日志,但它没有在logcat中显示任何内容。 This problem only occur in Oreo and run well in all other Android versions, also runs well when application is in background. 此问题仅发生在Oreo中,并且在所有其他Android版本中运行良好,在应用程序处于后台时运行良好。

public class MainActivity extends AppCompatActivity {

   AlarmManager am;
    TimeAlarm timeAlarm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        setOneTimeAlarm();
    }

    public void setOneTimeAlarm() {
        Intent intent = new Intent(this, TimeAlarm.class);

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

        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
    }

    public void setRepeatingAlarm() {
        Intent intent = new Intent(this, TimeAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("ondestroy","ondestroy");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("onstart","onstart");

        IntentFilter intentFilter=new IntentFilter("my.custom.action.tag.fordemo");
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        registerReceiver(timeAlarm,intentFilter);
    }
}

Code Of broadcast receiver, when I have removed the application from background it stopped working. 代码广播接收器,当我从后台删除应用程序时,它停止工作。

public class TimeAlarm extends BroadcastReceiver {

    NotificationManager nm;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {
    nm = (NotificationManager) 
    context.getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel mChannel = new NotificationChannel(
                        channelId, channelName, importance);
                nm.createNotificationChannel(mChannel);
            } else {

            }
            CharSequence from = "Nithin";
            CharSequence message = "Crazy About Android...";
            PendingIntent contentIntent = 
            PendingIntent.getActivity(context, 0, new Intent(), 0);
            //Notification notif = new Notification(R.drawable.logo, 
           "Crazy About Android...", System.currentTimeMillis());
            NotificationCompat.Builder notification = new 
            NotificationCompat.Builder(context.getApplicationContext());
            // notification.setContentIntent(pintent);
       notification.setTicker(from).setSubText(from).setSmallIcon(R.drawable.logo);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notification.setChannelId(channelId);
            }

            Notification notification1 = notification.build();
            notif.setLatestEventInfo(context, from, message,contentIntent);
            nm.notify(1, notification1);
        }
    }        

It shouldn't be working when in the background on any version of the OS. 它在任何版本的操作系统的后台应该不起作用。 You're registering the receiver in onStart, then unregistering in onStop. 您正在onStart中注册接收器,然后在onStop中取消注册。 That means the receiver, to the OS, does not exist after onStop is processed. 这意味着在处理onStop之后,OS的接收器不存在。 If you're seeing it work on other versions of the OS, that's actually a bug. 如果您看到它在其他版本的操作系统上运行,那实际上就是一个错误。

Sure, your broadcast is killed when your application is closed. 当然,您的broadcast在您的申请被关闭时被杀死。 If you dont unregisterReceiver in onStop / onDestroyed , you will have a leak issue. 如果您在onStop / onDestroyed unregisterReceiver onDestroyed ,则会出现泄漏问题。 To avoid it, you should implement a Service (and call registerReceiver(timeAlarm,intentFilter); in your service) which runs in the background even when your application is closed. 为避免这种情况,您应该实现一个Service (并在您的服务中调用registerReceiver(timeAlarm,intentFilter);即使您的应用程序关闭,它也会在后台运行)。

P/s: remember to startForeground to prevent service from being killed by system in Android 8.0 or above. P / s:记得startForeground以防止服务在Android 8.0或更高版本中被系统杀死。

You have to add alarm permission in your manifest 您必须在清单中添加警报权限

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

And also To register your broadcast 还要注册你的广播

    <receiver
        android:name=".broadcast.ServiceBroadcast"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServices">
        <intent-filter>
        <action android:name="restart_services"/>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM