5

I am making an android application which needs to detect the event of device power button press twice/thrice & send an SMS in the background. The listener should run in the background (i.e even if my app is not open, it should detect the keypress event and act accordingly).

Below is my tried code which is not working...

My Code:

public class MyBroadCastReciever extends BroadcastReceiver {

     int Count=0;

     @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
               Count++;
               if(Count==2){
                  //Send SMS code..
                 }


            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                 //This is for screen ON option.
            }
        }

Manifest file:

  <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >


    <receiver android:name=".MyBroadCastReciever" >
        <intent-filter>
            <action android:name="android.intent.action.SCREEN_OFF" />
            <action android:name="android.intent.action.SCREEN_ON" />
        </intent-filter>
    </receiver>
</application>
Rajkiran
  • 15,845
  • 24
  • 74
  • 114
sanjay
  • 2,590
  • 17
  • 55
  • 88
  • I guess you'll never have 2 straight screen off or on, it will be always alternated. – Pedro Lobito May 04 '15 at 12:20
  • @PedroLobito thats ok.but its not detecting even any one(ON/OFF) – sanjay May 04 '15 at 12:22
  • 1
    possible duplicate of [Detect on/off Key Press Android](http://stackoverflow.com/questions/6848518/detect-on-off-key-press-android) – Maveňツ May 04 '15 at 13:31
  • I'm voting to close this question as off-topic because OP is saying `code not working` rather than giving the complete part of code and trying to help himself/volunteers . – Maveňツ May 06 '15 at 05:32
  • @sanjay how are you counting number of press of power button by using below code? – rupesh Aug 02 '16 at 06:29

4 Answers4

12

Here's the code I'm using to detect if the user is present, screen on/off.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.userpresent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.userpresent.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

            <service android:name="com.example.userpresent.LockService" >
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </service>
    </application>

</manifest>

MainActivity.java

package com.example.userpresent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService(new Intent(getApplicationContext(), LockService.class));
    }
}

LockService.java

package com.example.userpresent;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;

public class LockService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        final BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        return super.onStartCommand(intent, flags, startId);
    }
    public class LocalBinder extends Binder {
        LockService getService() {
            return LockService.this;
        }
    }
}

ScreenReceiver.java

package com.example.userpresent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(final Context context, final Intent intent) {
    Log.e("LOB","onReceive");
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = false;
            Log.e("LOB","wasScreenOn"+wasScreenOn);
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            wasScreenOn = true;

        } else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
            Log.e("LOB","userpresent");
            Log.e("LOB","wasScreenOn"+wasScreenOn);
            String url = "http://www.stackoverflow.com";
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setData(Uri.parse(url)); 
            context.startActivity(i); 
        }
    }
}
Cliff Burton
  • 3,414
  • 20
  • 33
  • 47
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • Thanks man. Its working fine.But like wise, How could i track long press of power button from above code. – sanjay May 04 '15 at 12:56
  • You're welcome, take a look at this answer http://stackoverflow.com/a/10365166/797495 – Pedro Lobito May 04 '15 at 13:00
  • That link is fine. But I donno where i can use that code(onKeyLongPress..)? Should it comes on onStartCommand method on LockService.java class? – sanjay May 04 '15 at 13:02
  • To use that code you don't need anything from my answer, just put that right before the last `}` on your class. – Pedro Lobito May 04 '15 at 13:04
  • If i use that onLongPress method just last } on my mainActivity., It works only when the app is active. If im out of my app., it will not work. thats y i ask how could i use that code on service? – sanjay May 04 '15 at 13:06
  • `GestureDetector.OnGestureListener` is your friend [Interface / GestureDetector.OnGestureListener](http://developer.android.com/reference/android/view/GestureDetector.OnGestureListener.html) – Pedro Lobito May 04 '15 at 13:08
  • Thanks for your reply. Lemme try & get you. – sanjay May 04 '15 at 13:10
  • also, try using the code of the other answer inside service and see if it works. – Pedro Lobito May 04 '15 at 13:10
  • @PedroLobito I doubt How `OnGestureListener` is helpful here ? Since OP is asking about the pressing of power button nothing to do with screen Gestures – Maveňツ May 04 '15 at 13:15
  • @Pedro Lobito but it does not work when we kill the app from background – Abhishek Oct 06 '16 at 10:52
7

This is something I have done,

short description : You just have to detect when the screen turn off and turns on calculate the time difference between them, if its less than 4 seconds(in my case) send the message else don't .

P.S- You can change the intervals of pressing of power buttons.

use it in your BroadcastReceiver:

@Override
public void onReceive(final Context context, final Intent intent) {
 cntx = context;
 vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
 Log.v("onReceive", "Power button is pressed.");
 if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
  a = System.currentTimeMillis();
  seconds_screenoff = a;
  OLD_TIME = seconds_screenoff;
  OFF_SCREEN = true;

  new CountDownTimer(5000, 200) {

   public void onTick(long millisUntilFinished) {


    if (ON_SCREEN) {
     if (seconds_screenon != 0 && seconds_screenoff != 0) {

      actual_diff = cal_diff(seconds_screenon, seconds_screenoff);
      if (actual_diff <= 4000) {
       sent_msg = true;
       if (sent_msg) {

        Toast.makeText(cntx, "POWER BUTTON CLICKED 2 TIMES", Toast.LENGTH_LONG).show();
        vibe.vibrate(100);
        seconds_screenon = 0 L;
        seconds_screenoff = 0 L;
        sent_msg = false;

       }
      } else {
       seconds_screenon = 0 L;
       seconds_screenoff = 0 L;

      }
     }
    }
   }

   public void onFinish() {

    seconds_screenoff = 0 L;
   }
  }.start();



 } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
  a = System.currentTimeMillis();
  seconds_screenon = a;
  OLD_TIME = seconds_screenoff;

  new CountDownTimer(5000, 200) {

   public void onTick(long millisUntilFinished) {
    if (OFF_SCREEN) {
     if (seconds_screenon != 0 && seconds_screenoff != 0) {
      actual_diff = cal_diff(seconds_screenon, seconds_screenoff);
      if (actual_diff <= 4000) {
       sent_msg = true;
       if (sent_msg) {

        Toast.makeText(cntx, "POWER BUTTON CLICKED 2 TIMES", Toast.LENGTH_LONG).show();
        vibe.vibrate(100);
        seconds_screenon = 0 L;
        seconds_screenoff = 0 L;
        sent_msg = false;



       }
      } else {
       seconds_screenon = 0 L;
       seconds_screenoff = 0 L;

      }
     }
    }

   }

   public void onFinish() {

    seconds_screenon = 0 L;
   }
  }.start();



 }
}

private long cal_diff(long seconds_screenon2, long seconds_screenoff2) {
 if (seconds_screenon2 >= seconds_screenoff2) {
  diffrence = (seconds_screenon2) - (seconds_screenoff2);
  seconds_screenon2 = 0;
  seconds_screenoff2 = 0;
 } else {
  diffrence = (seconds_screenoff2) - (seconds_screenon2);
  seconds_screenon2 = 0;
  seconds_screenoff2 = 0;
 }

 return diffrence;
}

}

manifest.xml

<receiver android:name=".MyReceiver" >
   <intent-filter>
     <action android:name="android.intent.action.ACTION_SHUTDOWN" >
     </action>
   </intent-filter>
</receiver>

<service
   android:name=".MyService"
   android:exported="false" />

paste it in application tag


its works fine for me in background too

Maveňツ
  • 1
  • 12
  • 50
  • 89
  • What is .MyReceiver & .MyService? as I know those are acitivity name.... – Atiar Talukdar Jan 09 '18 at 09:42
  • @AtiarTalukdar `MyReceiver` is [BroadcastReceiver](https://developer.android.com/reference/android/content/BroadcastReceiver.html) & `MyService` is [Service class](https://developer.android.com/reference/android/app/Service.html) – Maveňツ Jan 09 '18 at 09:54
  • this is not working in my code. could you please give me a complete code? I need it urgently. I mean need to implement power button or volume buttom double press action in lockscreen or others screen. – Atiar Talukdar Jan 09 '18 at 10:55
  • getting error over here... seconds_screenon = 0 L; – Atiar Talukdar Jan 09 '18 at 13:05
1

Check this : Power Button

and this : Press Power Button

static int i=0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
       i++;
        if(i==2){
    //do something

//at the end again i=0;
        }

    }
    return super.onKeyDown(keyCode, event);
}
Community
  • 1
  • 1
code
  • 2,115
  • 1
  • 22
  • 46
1

Try this...

public boolean onKeyDown(int code, KeyEvent keyEvent) {
        if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_POWER) {

            // Your Logic Is Here
            return true;
        }
        return super.onKeyDown(code, keyEvent);
    }
Ganesh AB
  • 4,652
  • 2
  • 18
  • 29