Search code examples
androidkotlinbroadcastreceiver

How to start an activity from BroadcastReceiver's onReceive() method when app is in background?


I want to start an activity from the onReceive() method of the BroadcastReceiver. This is the code i am using:

class TimeReminderReceiver : BroadcastReceiver() {
     override fun onReceive(p0: Context?, p1: Intent?) {
         println("RECEIVED")

         val i = Intent(p0!!, TimeReminderActivity::class.java)
         i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
         p0.startActivity(i)
     }
}

There are many answers for this question in stackoverflow, i tried all of it and none of it is working for me. The app just prints RECEIVED and stays there. Nothing shows at the logcat, no exception, nothing. I have added the receiver in the mainfest also.

<receiver
        android:name=".receivers_and_activities.TimeReminderReceiver" />

Whats the problem with this code?

EDIT:

Code that calls the broadcast:

val intent = Intent(this@MainActivity, TimeReminderReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this@MainActivity, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT)
val am = this@MainActivity.getSystemService(Context.ALARM_SERVICE) as AlarmManager
am.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

Solution

  • As you commented out you are trying to launch an Activity when your App is in Background on Android 10 (API level 29).

    From Android (API level 29) they put some restrictions to open an Activity when your App is in Background.

    Android 10 (API level 29) and higher place restrictions on when apps can start activities when the app is running in the background.

    You can find out here Restrictions on starting activities from the background.

    They have also mentioned that

    In nearly all cases, apps that are in the background should display time-sensitive notifications to provide urgent information to the user instead of directly starting an activity. Examples of when to use such notifications include handling an incoming phone call or an active alarm clock.

    So to overcome this behavior instead of calling your App when it is in the background you should show high-priority notification with a full-screen intent.

    For more information on High-Priority Notification and Full-Screen Intent, you can check it here Display time-sensitive notifications