Mithilesh Izardar
Mithilesh Izardar

Reputation: 2227

getting event for phone lock when app is active in android

I am developing an application which need security and login system. I am using preferences to save session data.

If any user goes out of application, onPause() method is getting called and the app clears all its preferences data but this is where I am getting problem, when user's screen is locked then onPause() method is getting called and it clears all data. I don't want to clear the data if users screen is locked.

I used BroadcastReceiver to achieve this but I want a optimized solution

 <receiver android:name=".SessionWakeBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
</intent-filter>
</receiver>

SessionWakeBroadcastReceiver code:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SessionWakeBroadcastReceiver extends BroadcastReceiver {

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


    if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
       //Some Action
    }

    else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
           //Some Action
    }
}

}

in onPause() method , can I get that which intent is getting called if its phone lock then i will not perform data clearing.

any help will be appericiated

Thanks in advance

Upvotes: 1

Views: 89

Answers (1)

earthw0rmjim
earthw0rmjim

Reputation: 19417

can I get that which intent is getting called if its phone lock

You may be looking for the Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON actions.

But keep the following in mind:

You cannot receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

To check if the screen is locked, you could do something like this:

KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (km.isKeyguardLocked()) {
    // locked
} else {
    // not locked
}

Upvotes: 1

Related Questions