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
  •  | 
  •  

Domanda

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

È stato utile?

Soluzione

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);
        }
    }
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top