AppWidgetProvider problem

2019-02-10 23:13发布

I have an AppWidgetProvider, and I need to do some initialization when a widget is first added to the home screen. I understand that the place to do it is in the onEnabled(Context context) method. My Problem is that this method is never called (As far as I can see in the logcat).

Here is my code:

public class MyMonitorWidget extends AppWidgetProvider{

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);

        Log.v("LOG", "Widget onEnabled");
        Intent intentToFire = new Intent(UpdateAlarmReceiver.ACTION_UPDATE_ALARM); 
        context.sendBroadcast(intentToFire);
    } 
...
}

And my appwidget-provider xml:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:initialLayout="@layout/widget_layout"
  android:minWidth="146dp" 
  android:minHeight="74dp"
  android:label="Monitor Widget"
  />

and in the manifest:

<receiver android:name="MyMonitorWidget" android:label="Monitor Widget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>
        <intent-filter>
        <action android:name="com.android.myMonitor.ACTION_NOTIFY_WIDGET"/>
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" 
        android:resource="@xml/monitor_widget_info"/>
    </receiver>

What do you think is the problem?

2条回答
Luminary・发光体
2楼-- · 2019-02-10 23:53

You need to add android.appwidget.action.APPWIDGET_ENABLED as another action:

    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
    </intent-filter>

Without that, you will not receive the broadcast that triggers onEnabled().

查看更多
爷、活的狠高调
3楼-- · 2019-02-11 00:19

Don't forget about android:exported property! I didn't receive onDelete() when android:exported was false

<receiver 
    ...
    android:exported="true"
    ... >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        <action android:name="android.appwidget.action.APPWIDGET_DELETED" />
        <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
        <action android:name="android.appwidget.action.APPWIDGET_DISABLED" />
    </intent-filter>

    <meta-data 
        android:name="android.appwidget.provider"
        android:resource=... />
</receiver>
查看更多
登录 后发表回答