【问题标题】:Android:Is it possible to detect a movement/shake with the help of widget on home screen?Android:是否可以借助主屏幕上的小部件来检测移动/震动?
【发布时间】:2013-11-22 22:50:38
【问题描述】:

我正在尝试为主屏幕制作一个 android 小部件,如果检测到移动,它将更改小部件图标。

我知道如何创建小部件以及如何使用 AppWidgetProvider RemoteViews 更改小部件图标, 我还可以使用Sensor.TYPE_ACCELEROMETERActivity 检测运动。但正如你所知,没有任何活动正在运行,我不知道 如何通过小部件检测运动,请分享您的想法。

我想到了一项服务,但不知道如何让它继续运行,它将检测抖动/运动,并可能在我的自定义 AppWidgetProvider 中设置一个静态变量 在更新时我可能会检查该静态变量的状态,如果它改变了,我可以更改小部件的图标。 提前致谢。

注意:我使用的是 API 级别 8。android:minSdkVersion="8"

解决方案: 我接受下面的答案,因为它帮助我搜索了我正在寻找的东西,最后我成功了,我就是这样做的

我对@9​​87654327@ 类的实现启动了一个自定义Service,该服务在实现SensorEventListener 的后端运行,我重写了一个方法onStartCommand 并创建了一个SensorManager 类的对象,并且还创建了一个Notification 的对象,它显示在通知区域中,我将通知作为前台启动。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (sensorManager == null) {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

        Notification notification = new Notification(R.drawable.MyIcon,"In Action", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, SayHello.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(this, "In Action","Service is running in foreground", pendingIntent);
        //This worked for me
        startForeground(ONGOING_NOTIFICATION_ID, notification);

    return START_NOT_STICKY;
}

【问题讨论】:

    标签: android android-widget accelerometer


    【解决方案1】:

    为了让它工作,我认为你需要使用foreground service(它有自己的通知让它继续运行)。

    这可能会对电池造成影响,因此您可能需要考虑替代方案。

    但是,您可能会感兴趣,而不是使用您自己的传感器算法:谷歌已经展示了如何处理“(最终用户)活动识别”,例如跑步/步行/...。 here's a link 关于它。它应该比创建自己的机制更有效。

    【讨论】:

    • 感谢您的回复,我不需要检测额外的移动,只需摇晃或移动移动[已经使用 android 内置 API],如果我能做到这一点,我将如何记住它一种应用程序,但是现在我将阅读您的第一个链接。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2014-03-05
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多