I use this code to start an activity when the power button is pressed 2 or more times but it doesn't work.
Here is my code for MyReceiver.java:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

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, About.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(i);
            }
        }
    }
}

And manifest file:

<receiver android:name="MyReceiver" android:enabled="true"/>
有帮助吗?

解决方案

You created a reciever but did not register it.

In your activity's oncreate method register for the receiver

@Override
protected void onCreate() {
    // initialize receiver
    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    final BroadcastReceiver mReceiver = new MyReceiver();
    registerReceiver(mReceiver, filter);

}

Anyways. You dont need broadcast receiver for Power button press event..

You can use this code

int i = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
 if(keyCode == KeyEvent.KEYCODE_POWER)
 {
    i++;
    if(i == 2)
    {
        // Do something you want
    }
 }
return super.onKeyDown(keyCode, event);
}

其他提示

Try to declare the receiver as follow

<receiver android:name="MyReceiver" android:enabled="true">   
<intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF" >
        </action>
        <action android:name="android.intent.action.SCREEN_ON">
        </action>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED">
        </action>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED">
        </action>
        <action android:name="android.intent.action.ACTION_SHUTDOWN">
       </action>
  </intent-filter>
</receiver>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top