【发布时间】:2013-11-22 22:50:38
【问题描述】:
我正在尝试为主屏幕制作一个 android 小部件,如果检测到移动,它将更改小部件图标。
我知道如何创建小部件以及如何使用 AppWidgetProvider RemoteViews 更改小部件图标,
我还可以使用Sensor.TYPE_ACCELEROMETER 和Activity 检测运动。但正如你所知,没有任何活动正在运行,我不知道
如何通过小部件检测运动,请分享您的想法。
我想到了一项服务,但不知道如何让它继续运行,它将检测抖动/运动,并可能在我的自定义 AppWidgetProvider 中设置一个静态变量
在更新时我可能会检查该静态变量的状态,如果它改变了,我可以更改小部件的图标。
提前致谢。
注意:我使用的是 API 级别 8。android:minSdkVersion="8"
解决方案: 我接受下面的答案,因为它帮助我搜索了我正在寻找的东西,最后我成功了,我就是这样做的
我对@987654327@ 类的实现启动了一个自定义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