我已经创建了一种发送SMS并在函数callfunction();下调用的方法
当用户按下四次电源按钮时,我想调用该函数,这不要求应用程序处于启动状态。

最佳答案

尝试使用Power Manager


  PARTIAL_WAKE_LOCK
  
  在API级别1中添加
  整数PARTIAL_WAKE_LOCK
  唤醒锁定级别:确保CPU在运行;屏幕和键盘背光将被允许熄灭。
  
  如果用户按下电源按钮,则屏幕将关闭,但CPU将保持打开状态,直到所有部分唤醒锁都已释放。
  
  常数值:1(0x00000001)


例:

//Initialize the Power Manager
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

 //Create a PARTIAL_WAKE_LOCK
 //This will keep the cpu running in the Background, so that the function will be called on the desired Time
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");

//Check if the WackLock is held (may throw erro if you try to acquire twice)
//TRUE --> Do nothing, all good
//FALSE --> Acquire the WakeLock
 if(!wl.isHeld()){
    wl.acquire();
 }

//*****
//You code to handel the Powerbutton comes here
//*****

//If the Repeating task is not active, release the Lock

//Check if the WackLock is held (may throw error if you try to release a none acquired Lock)
//TRUE --> Release Lock
//FALSE --> Do nothing, all good
 if(wl.isHeld()){
    wl.release();
 }


要处理电源按钮,请查看以下文章:
How to hook into the Power button in Android?

这只是一个假设,如果仍然不起作用,是否可以发布一些Logs或项目的更多代码片段:)

10-08 05:43