如何使用安卓在手机闲置时设置闹钟?

2022-09-03 15:33:31

嗨,我想在手机未被触摸时设置闹钟。如果屏幕近2分钟没有被触摸,警报声就会响起。我该怎么做?任何人都可以帮助我吗?提前致谢。


答案 1

通过以下代码传递警报服务。这将找到您的设备处于空闲状态的时间。

空闲.java

Handler hl_timeout = new Handler();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try{
        hl_timeout.postDelayed(DoOnTimeOut, 15000);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
}

//  Toast
Thread DoOnTimeOut = new Thread() {
    public void run() {
        try{
            Toast.makeText(getApplicationContext(), "System is idle", Toast.LENGTH_LONG).show();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
};

@Override
public void onUserInteraction()
{
    super.onUserInteraction();
    //Remove any previous callback
    try{
    hl_timeout.removeCallbacks(DoOnTimeOut);
    hl_timeout.postDelayed(DoOnTimeOut, 15000);
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

希望这对您有所帮助。


答案 2

您可以创建 AlarmService 来播放声音,即使应用程序/设备处于空闲状态

扩展方法 onUser活动类的交互操作以重置计时器并重新启动两分钟。


推荐