简体   繁体   中英

Starting activity from alarm broadcast receiver even when user clicked home button

I'm searching whole day how to do this in my opinion simple task...i have an alarm in my app and when it goes off i want to bring my app in front of the user screen so he can turn the alarm off... In my activity i have set up an intent to call the reciever...

registerReceiver(mReceiver, new IntentFilter("sample") );
PendingIntent pendingIntent = PendingIntent.getBroadcast( MapActivity.this, 0, new Intent("sample"),0 );
AlarmManager alarmManager = (AlarmManager)(MapActivity.this.getSystemService( Context.ALARM_SERVICE ));

and this is my onRecieve method

@Override
  public void onReceive(Context context, Intent intent) {

    Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
    Uri notifikacijaAlarma = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    final Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notifikacijaAlarma);
    r.play();

    PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "TRAININGCOUNDOWN");
    wl.acquire();

    Intent i = new Intent(getBaseContext(), GlavniIzbornik.class);
    i.setAction(Intent.ACTION_MAIN);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    i.setFlags(Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);

    startActivity(i);
    wl.release();

}               

so my alarm goes off even when i go to another application or do anything else on the phone...it shows Toast and plays the ringtone but it doesn't bring my app to front and when i manually go to my app it starts activity but i just can't get it so it will bring my app to front.

does anyone have some suggestion about this?

PS i know i should play ringtone from my alarm activity...i just wanted to see if the whole code gets executed...

You are starting the Activity by an explicit Intent . Delete lines i.setAction(...) and i.setCategory(...) . These are used in manifest to show this Activity in launcher.

Next according to documentation you do not set Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY yourself.

Do not EVER use getBaseContext() , in BroadcastReceiver.onReceive(...) use context as in new Intent(context, GlavniIzbornik.class); or context.startActivity(i) . In Activity or Service use this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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