In this code I try to show a toast two times inside a BroadcastReceiver. There is no problem with the first one, when previously I created an activity, but the second one the toast doesn't show. What is the problem? How can I show a toast without an activity? The problem could be that if just after showing a toast the application ends the toast does not show up?
class MyReceiver : BroadcastReceiver() {
val PREFS_NAME = "MyPrefsFile"
override fun onReceive(context: Context, intent: Intent) {
if (intent.action.equals(Intent.ACTION_USER_PRESENT)) { //when unlock
val settings = context.getSharedPreferences(PREFS_NAME, 0)
var veces = settings.getInt("veces", 0)
val limite = settings.getInt("limite", 3)
veces++
val editor = settings.edit()
editor.putInt("veces", veces)
editor.apply()
if (veces % limite == 0) { //
val intent1 = Intent(context, MainActivity::class.java)
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent1)
Toast.makeText(context, "Veces $veces", Toast.LENGTH_LONG).show() //works
} else {
Toast.makeText(context, "Veces $veces", Toast.LENGTH_LONG).show() //It doesn't work
}
}
}
}
I suppose it is not the best solution but I have achieved what I wanted to do by creating a second transparent activity and I show the toast from within this transparent activity.I wonder if it is possible to show a toast from a BroadcasReceiver, without creating an activity.