You need to save this information yourself. I usually use application settings, but you can use anything. Typically, widgets use services for communication, so your code that does things probably works in the service, but using preferences, allows access to any part of your application.
In your widget class, which extends AppWidgetProvider, onEnabled is called when the widget is placed on the main screen, and the onDeleted call (usually) is called when it is removed. onDisabled is called when all copies are deleted.
So, in the code of the provider of your widget:
@Override public void onEnabled(Context context) { super.onEnabled(context); setWidgetActive(true); context.startService(new Intent(appContext, WidgetUpdateService.class)); } @Override public void onDisabled(Context context) { Context appContext = context.getApplicationContext(); setWidgetActive(false); context.stopService(new Intent(appContext, WidgetUpdateService.class)); super.onDisabled(context); } private void setWidgetActive(boolean active){ Context appContext = context.getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(Constants.WIDGET_ACTIVE, active); edit.commit(); }
Elsewhere in the code, you can check if the widget is active:
public boolean isWidgetActive(Context context){ Context appContext = context.getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getBoolean(Constants.WIDGET_ACTIVE, false); }
larsona1
source share