Check If A Widget Is Exists On Homescreen Using Appwidgetid
Solution 1:
Congratulations, you've encountered phantom appwidgets. It appears to be documented on the Android issue tracker. They usually occur when the configuration activity for an appwidget is canceled, though it seems to be through improper implementation of the configuration activity; developers neglect to include the appwidget ID as an extra when setting the activity result to RESULT_CANCELED
. (even Google's ApiDemos sample application neglects to do this!)
The proper implementation is like this:
publicclassAppWidgetConfigActivityextendsActivity {
privateint appWidgetId;
private Intent resultValue;
protectedvoidonCreate(bundle saved) {
super.onCreate(saved);
// get the appwidget id from the intentIntentintent= getIntent();
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
// make the result intent and set the result to canceled
resultValue = newIntent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_CANCELED, resultValue);
// if we weren't started properly, finish hereif (appwidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
/* ... */
}
/* ... */privatevoidfinishConfigure() {
/* finish configuring appwidget ... */
setResult(RESULT_OK, resultValue);
}
}
Thus far I know of no way to detect the presence of a phantom appwidget without doing your own bookkeeping. I suggest storing a SharedPreferences value indicating that the configuration activity was not canceled and then querying this value in your other code. You can also use this information to "delete" a phantom widget if you come across one. In your appwidget configuration activity:
privatevoidfinishConfigure() {
/* finish configuring appwidget ... */setResult(RESULT_OK, resultValue);
String key = String.format("appwidget%d_configured", appwidgetId);
SharedPreferences prefs = getSharedPreferences("widget_prefs", 0);
prefs.edit().putBoolean(key, true).commit;
}
Then you can check that you have at least one non-phantom appwidget like so:
AppWidgetManagerappWidgetManager= AppWidgetManager.getInstance(context);
AppWidgetHostappWidgetHost=newAppWidgetHost(context, 1); // for removing phantomsSharedPreferencesprefs= getSharedPreferences("widget_prefs", 0);
booleanhasWidget=false;
int[] appWidgetIDs = appWidgetManager.getAppWidgetIds(newComponentName(context, Widget.class));
for (inti=0; i < appWidgetIDs.length; i++) {
intid= appWidgetIDs[i];
Stringkey= String.format("appwidget%d_configured", id);
if (prefs.getBoolean(key, false)) {
hasWidget = true;
} else {
// delete the phantom appwidget
appWidgetHost.deleteAppWidgetId(id);
}
}
if (hasWidget) {
// proceed
} else {
// turn off alarms
}
Post a Comment for "Check If A Widget Is Exists On Homescreen Using Appwidgetid"