【问题标题】:How to start an activity if the power button is pressed (x) no of times in my android app?如果在我的 android 应用程序中没有按下电源按钮 (x) 次,如何启动活动?
【发布时间】:2014-06-16 08:23:03
【问题描述】:

还请解释它是如何工作的。当我的应用程序关闭时,这也应该有效。(它应该在后台运行)

【问题讨论】:

标签: android logic


【解决方案1】:

您需要为此注册广播接收器
当应用程序在后台关闭时这项工作

public class MyReceiver extends BroadcastReceiver 
{
private static int countPowerOff = 0;

public MyReceiver ()
{

}

@Override
public void onReceive(Context context, Intent intent)
{
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
    {    
        Log.e("In on receive", "In Method:  ACTION_SCREEN_OFF");
        countPowerOff++;
    }
    else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
    {
        Log.e("In on receive", "In Method:  ACTION_SCREEN_ON");
    }
    else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
    {
        Log.e("In on receive", "In Method:  ACTION_USER_PRESENT");
        if (countPowerOff > 2)
        {
            countPowerOff=0;
            Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        }
    }
  }
}

【讨论】:

  • 如果我输入 (countPowerOff > 6) 那么用户必须按下电源按钮多少次
  • 超过 6 次,但记得在清单文件中声明接收者以运行此
  • 我试过了,但它不起作用顺便说一句我在清单中声明了接收者,请帮助
  • 如果您从某个地方获取此代码,请提供链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
相关资源
最近更新 更多