How to start an activity if the power button is pressed (x) no of times in my android app?

StackOverflow https://stackoverflow.com/questions/23380897

  •  12-07-2023
  •  | 
  •  

문제

Please also explain how it works. This should also work when my app is closed.(it should be running in background)

도움이 되었습니까?

해결책

you need to register broadcast rceciever for this
This work when app is closed in background

public class MyReceiver extends BroadcastReceiver 
{
private static int countPowerOff = 0;

public MyReceiver ()
{

}

@Override
public void onReceive(Context context, Intent intent)
{
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
    {    
        Log.e("In on receive", "In Method:  ACTION_SCREEN_OFF");
        countPowerOff++;
    }
    else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
    {
        Log.e("In on receive", "In Method:  ACTION_SCREEN_ON");
    }
    else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
    {
        Log.e("In on receive", "In Method:  ACTION_USER_PRESENT");
        if (countPowerOff > 2)
        {
            countPowerOff=0;
            Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }
    }
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top