简体   繁体   中英

Android: Overriding the power button in a Fragment

I'm working on a thing where I need to override the power button in a Fragment when pressed. I did this successfully, however, the screen turns off when the power button is pressed.

I did a quick search and came across a few posts like this , this , and this . Some say it's doable and others say it's not. My question is that is this even doable? If so, any idea how to go about this?

You can use this to prevent screen from locking

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

While using in fragment

getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

Use a BroadcastReceiver and listen for the android.intent.action.SCREEN_OFF or Intent.ACTION_SCREEN_OFF which is sent when power button is pressed (and screen is on). What i think is that overriding the power button is not possible , because of security issues.

What you are doing is not advisable. However you can write a broadcast receiver and then the screen gets locked, wake it up using AlarmManager. Below is the code.

    @Override
public void onReceive(Context context, Intent intent) {
if ((intent.getAction().equals(Intent.ACTION_SCREEN_OFF))) {

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "TEST");
wakeLock.acquire();

AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent inten = new Intent(context,NewActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0, inten, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,  100, pi);
}
}   

// Finish your WakeLock HERE. call this method after U put the activity in front or when u exit from the new activity.
public void finishWakeLocker(){
if (wakeLock != null) 
wakeLock.release();  
}

You cannot override the power button functionality however you can prevent system from showing dialog on long press of a power button using following.

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(!hasFocus) {
           Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            sendBroadcast(closeDialog);
        }
    }

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