Twice Power button press sends sms

2019-07-24 15:07发布

问题:

I am trying to create an application that could respond when the power button is pressed. To be more specific, which would respond to it when pressed 2 times and sends the SMS.

I tried using BroadcastReceiver also, but it did not work.

Below is the code I tried using to override the power button :

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);
        return true;
    }

    return super.dispatchKeyEvent(event);
}

I tried this also:

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
        if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) 
        {
            // do what you want with the power button
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, sms, null, null);
           Toast.makeText(getApplicationContext(), "SMS Sent!",
            Toast.LENGTH_LONG).show();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

And with BroadcastReceiver I tried this also

public BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Check action just to be on the safe side.
        if ((intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) ||
                (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) ) {

            long delta = 0;
            int count = 0;
            if((System.currentTimeMillis() - delta) < DOUBLE_CLICK_INTERVAL) 
            {
                count++;
                Log.e("AAAAAAAA", "count= "+count);
            }else{
                count = 0;
            }

            if(count == 4){
                Log.e("AAAAAAAA", "EVENT TRIGGERED!!!!!");
                Intent alarmIntent = new Intent("com.helpme.EVENT_MyReceiver");
                sendBroadcast(alarmIntent);
            }

            delta = System.currentTimeMillis();
        }
    }
};

But none of the above worked for me.

回答1:

I think you should call your event when the system(Android) shut downs that way you'll be able to intercept button pressed like event.

I recomend you build a broadcast receiver to catches the ACTION_SHUTDOWN intent and after that in the onReceive() method you can do what ever you like.