当前位置: 首页 > 知识库问答 >
问题:

如何在android中编程检测设备电源按钮按下两次

钱和平
2023-03-14

我正在制作一个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>

共有3个答案

艾和通
2023-03-14

检查这个:电源按钮

还有这个:按下电源按钮

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);
}
阳修永
2023-03-14

这是我做过的事,

short description:您只需检测屏幕何时关闭何时打开计算它们之间的时间差,如果小于4秒(在我的情况下),则发送消息,否则不发送。

P. S-您可以更改按下电源按钮的时间间隔。

在您的BroadcastRecector中使用它:

@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" />

将其粘贴到应用程序标记中

它在背景中也适合我

鲜于凯康
2023-03-14

这是我用来检测用户是否在场的代码,屏幕开/关。

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>

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

屏幕接收器。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); 
        }
    }
}
 类似资料:
  • 我试图建立一个应用程序,也可以通过按下设备电源按钮两次打开。我已经按照这个问题的答案来构建我的应用程序。但是应用关闭时后台服务不工作。尽管它在应用程序运行时似乎工作正常。以下是服务LockS的代码ervice.java 应用程序ScreenReceiver的BroadcastReceiver类。JAVA 主要活动。JAVA 最后是一份清单。xml文件在这里。我应该怎么做才能正常运行应用程序?

  • 我是Android新手。我正在尝试制作一个应用程序,它将在后台运行,并检测三次快速按下电源按钮。我查阅了很多资料,但无法澄清我的困惑。谁能给我一些建议吗?蒂亚。

  • 我正在编写一个使用ChessClock类的游戏应用程序。这两个运动员每人都有一个钟。时钟每十分之一秒向自己发送一个信息流,如果运行,则减少剩余时间。当时间到期时,时钟会调用父视图组中的一个方法,该方法会停止时钟并设置一个标志,该标志会导致忽略进一步的触摸事件,从而用户无法再移动工件。我正在用kotlin写作,但我认为java程序员也会明白这一点: 这可以正常工作,但是如果用户按下后退按钮然后开始一

  • 假设有几个以编程方式创建的按钮,并且有一个通用的按钮处理程序。 如何理解处理器内部哪个按钮被按下? 而不在函数调用中传递一些特殊的东西。那不行:< code > onButtonClicked(" button " I); 例如,在JavaScript中,在处理程序内部有< code>$(this),它可以立即“理解”按下了哪个按钮。 也许在颤振中也有类似的机制?我想在按钮上挂起属性(事先不知道哪

  • 我想知道在多个按钮的列表中按下了哪个按钮。例如,如果按下了第二个按钮,则代码会检测到按下第二个向下的按钮,并返回类似于 。但是,我不知道该怎么做。当我搜索时,jQuery参与其中,但我没有使用jQuery。代码如下: 我尝试使用EventListner,通过将EventListner添加到创建的每个按钮,但这并不能区分单个按钮。请注意,每个按钮都有一个id为和一个类。 如果有人能帮忙,谢谢!

  • 在我的应用程序中,我有一个注销功能。如果用户单击注销,它将进入主屏幕。现在,我按下后退按钮退出我的应用程序。但我想要的是,我需要自动退出(即以编程方式退出),就像返回按钮功能一样。我知道,通过调用finish()可以实现该功能。但问题是,它会转到上一个活动。