Check Widget is Placed on Android Screen

后端 未结 4 1252
广开言路
广开言路 2020-12-15 10:01

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 ho

4条回答
  •  没有蜡笔的小新
    2020-12-15 10:58

    I know it's an old question, but looking at this today I saw that there are a couple of problems with the accepted answer from @larsona1:

    1. if the user cleared the shared preferences - there's still widget, but the app won't know about it.
    2. if the user regret between "add widget" and before pressing "ok" - onEnabled will be called anyway, and a widget will be registered in the home screen even though there is no widget, and no way to remove it later. (it may be a bug in ADT home launcher).

    I found a solution to the first problem. No shared preferences are needed at all, since it's unreliable anyway. It has to be checked in runtime.

    // in some class you define a static variable, say in S.java
    static boolean sWidgetMayExist = true;
    

    In your widget provider:

    // MyAppWidgetProvider.java
    // to respond to runtime changes, when widgets are added and removed
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        S.sWidgetMayExist = true;
    }
    
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        S.sWidgetMayExist = true;
    }
    

    And, in your service code add this:

    AppWidgetManager manager = null;
    RemoteViews views = null;
    ComponentName widgetComponent = null;
    
        // ..and in your update thread
    
        if (!S.sWidgetMayExist) { return; }
    
    if (manager == null || widgetComponent == null) {
        widgetComponent = new ComponentName(c,
                MyAppWidgetProvider.class);
        manager = AppWidgetManager.getInstance(c);
    }
    
    if (manager.getAppWidgetIds(widgetComponent) == null) {
        S.sWidgetMayExist = false;
    }
    

提交回复
热议问题