簡體   English   中英

如何在android中以編程方式檢測設備電源按鈕兩次

[英]How to detect device power button press twice in android programmatically

我正在制作一個Android應用程序,需要檢測設備電源按鈕事件按兩次/三次並在后台發送短信。 監聽器應該在后台運行(即使我的應用程序未打開,它應該檢測到按鍵事件並相應地采取行動)。

以下是我嘗試過的代碼無效...

我的代碼:

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.
            }
        }

清單文件:

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

這是我用來檢測用戶是否在場,屏幕開/關的代碼。

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); 
        }
    }
}

這是我做過的事情,

short description :你只需檢測屏幕何時turn offturns on計算它們之間的時差,如果它小於4秒( in my case )發送消息,否則不要。

PS-您可以更改pressing of power buttons的間隔。

在你的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" />

將其粘貼到application標記中


在背景中 對我來說 也很好

檢查一下: 電源按鈕

並且: 按下電源按鈕

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);
}

嘗試這個...

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

            // Your Logic Is Here
            return true;
        }
        return super.onKeyDown(code, keyEvent);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM