Home » Android » android – Activity not started when the app is not running (when called from broadcastReceiver-Exceptionshub

android – Activity not started when the app is not running (when called from broadcastReceiver-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m using AlarmManager to show snooze screen/Activtiy and I’m using a BroadcastReceiver to open this ACtivity. everything just works fine but when the App is not running, even when it is in the background the activity does not start.
here’s my BroadcastReceiver code:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, SnoozeActivity.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}

Activity which I want to call in the background

SnoozeActivity.java


public class SnoozeActivity extends AppCompatActivity {

    SwipeButton btnSwipe;
    Clock mClock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_snooze);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        btnSwipe = findViewById(R.id.btnSwipe);
        mClock = findViewById(R.id.clock);

        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        final Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();
        Toast.makeText(this, "Alarm Ringing", Toast.LENGTH_SHORT).show();

        btnSwipe.setOnStateChangeListener(new OnStateChangeListener() {
            @Override
            public void onStateChange(boolean active) {
                r.stop();
                Toast.makeText(getApplicationContext(), "Alarm Stopped", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }
}
How to&Answers:

Try this

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, SnoozeActivity.class);
        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}