I am trying to make an android widget for home screen, which will change the widget icon, if a movement is detected.
I know how to create a widget and how to change widget icon using AppWidgetProvider
RemoteViews
,
I am also able to detect movement using Sensor.TYPE_ACCELEROMETER
, with in an Activity
. but as you know there is no activity running and I have no idea
how to detect motion through a widget, Please share your thoughts.
I thought of a service, but don't know how to make it keep running which will detect shake/motion and might set a static variable in my custom AppWidgetProvider
where on update i might check the status of that static variable if its changed i can change icon of widget.
Thanks in advance.
Note: I am using API level 8. android:minSdkVersion="8"
Solution: I am accepting the answer bellow because it helped me to search what I was looking for and finally I succeeded, Here is how I did it
My implementation of AppWidgetProvider
class start a custom Service
, This service runs at the back end which implements SensorEventListener
, I have overridden a method onStartCommand
and created an object of SensorManager
class, and also created an object of Notification
, which is displayed in notification area, i started my notification as foreground.
@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;
}
in order for this to work, i think you need to use a foreground service (which has its own notification to let it keep running).
this could take a toll on the battery, so you might want to think of an alternative.
however, there is something that could be interesting for you, instead of using your own sensors algorithm: google has shown how to handle "(end user) activities recognition", like running/walking/... . here's a link about it. it's supposed to be more efficient than creating your own mechanism.