如何创建一个在屏幕锁定时在震动事件上激活的 android 应用程序? [英] How to create an android app that activates on shake events when screen locked?

查看:26
本文介绍了如何创建一个在屏幕锁定时在震动事件上激活的 android 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个应用程序,它在设备抖动时 ** 启动 Main Activity,即使在屏幕锁定时也是如此.任何人都可以解释如何做到这一点?

I want to create an app that **starts the Main activity whenever the device shakes, even when screen locked. Can anyone explain how to do that?

我有一个想法,它需要创建一个在后台运行的服务,但我在实际编码方面很挣扎,不知道如何去做.

I have an idea that it requires to create a service that runs in background, but I am struggling with actual coding and don't know how to do it.

推荐答案

要创建一个对震动事件敏感的应用程序:

To create an app which is sensitive to shake event:

A. 在清单中 - 注册一个引导接收器.它将确保您的应用程序始终处于激活状态设备重启后:

A. In manifest - register a boot receiver. It will make sure your app will always be activated after device restart:

  <receiver android:name=".OnBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>



B. 创建一个摇动事件监听器类:



B. Create a shake event listener class:

class ShakeEventListener implements SensorEventListener {
        @Override
        public void onSensorChanged(SensorEvent event) {
              handleShake(event); // see below
        }
}



C. 启动接收器实现 - 为 TYPE_ACCELEROMETER 事件注册一个震动监听器



C. Boot receiver implementation - register a shake listener for TYPE_ACCELEROMETER events

public class OnBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent){
        SensorManager sManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sManager.registerListener(new ShakeEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL); // or other delay
    }
}



D. 如果检测到摇晃动作 - 开始您的主要活动:



D. If Shake motion is detected - start your main activity:

void handleShake(event) {
    if (shake movement detected) {
         // start main activity
         Intent intent = new Intent(getBaseContext(), myActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(intent);
    }
}



我们唯一遗漏的是检测到晃动"逻辑.



The only thing we left out is the "shake movement detected" logic.

在这里您可以找到相当不错的基本实现.使用函数 onSensorChanged().你可能需要改变它直到你做对为止.

Here you can find a reasonably good base implementation. Use function onSensorChanged(). You will probably need to variate on it until you get it right.



权限:



Permissions:

  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

这篇关于如何创建一个在屏幕锁定时在震动事件上激活的 android 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆