Search code examples
androidscreenbroadcastreceiveralarm

restart an app when Screen is OFF


My app is finishing when user touch the screen. For this, on onTouch() method I have

Intent intent = new Intent(getBaseContext(), FinActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();

where FinActivity class is this one :

public class FinActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new AlarmReceiver();
        registerReceiver(mReceiver, filter);

        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + (60 * 1000),
                System.currentTimeMillis() + (60 * 1000), pendingIntent);
        finish();
    }

I want to restart my app when screen is OFF. I have this AlarmReceiver class :

public class AlarmReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

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

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            System.out.println("Screen OFF");
            wasScreenOn = false;

                Intent i = new Intent(context, SplashScreen.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            System.out.println("Screen ONN");
            wasScreenOn = true;
        }
    }

}

but after 60 seconds I get NullPointerException at this line : intent.getAction().equals(Intent.ACTION_SCREEN_OFF)

Where is my mistake ? What i do wrong?

Thanks in advance.


Solution

  • If you just want to know whether your screen is turned on or off, you can use PowerManager class of android it is from api level 1.You can use isScreenOn() method for knowing status of screen.

    You can get more details http://developer.android.com/reference/android/os/PowerManager.html here.