I'm new to Android. I want to create a widget which will show current battery level. After reading several tutorials I did the following. Created class which extends AppWidgetProvider. In its onUpdate and onEnabled methods registered Broadcast reciever with intent filter ACTION_BATTERY_CHANGED. In onRecieve method TextView is updated with current battery level.
Here they are:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
ComponentName cn = new ComponentName(context, BatteryAppWidgetProvider.class);
context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
appWidgetManager.updateAppWidget(cn, this.views);
}
@Override
public void onReceive(Context context, Intent intent) {
Integer level = intent.getIntExtra("level", -1);
this.views.setTextViewText(R.id.battery_level, level.toString() + "%");
ComponentName cn =
new ComponentName(context, BatteryAppWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, this.views);
super.onReceive(context, intent);
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
And it works for some time - I can see it in the DDMS. But after some time passes or after I launch a lot of other applications. My process disappears from DDMS. I think Android is just deleting it to free up more memory. So the question is how can I avoid this? How can I make my process to be always alive?
If there is something you want android to do when the user is not interacting with the widget/application, you should use a service.
It is meant to be used for tasks that require no user interaction and is especially great for checking something over and over. No guarantee that the os still wont kill it eventually, but it kept alive as long as possible.