Search code examples
androidwidgethomescreen

Check Widget is Placed on Android Screen


Can someone tell me how to check that my widget have been placed on the homescreen?

I have some code in my app that should run only if the widget is placed on the homescreen.


Solution

  • You need to store that information yourself. I usually use the application preferences, but you could use anything. Generally widgets use services to communicate, so your code that does stuff is likely in a service, but using the preference allows any portion of your app to access this.

    In your widget class that extends AppWidgetProvider the onEnabled is called when the widget is put on a homescreen and the onDeleted is (usually) called when it's removed. onDisabled is called when all copies are removed.

    So in the code of your widget provider:

    @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 code, you would check to see if the widget is active by:

    public boolean isWidgetActive(Context context){
        Context appContext = context.getApplicationContext();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getBoolean(Constants.WIDGET_ACTIVE, false);
    }