Why widget does not work after reboot?

2019-02-11 03:31发布

I have this simple widget and when I click on it, it should open my activity, it works, but it doesn't work after reboot. I must delete and then again add widget to my homescreen, because when I click on widget widget doesn't respond and doesn't open my activity. So where is the problem?

Code:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        for(int i=0; i<N; i++){
            int appWidgetId = appWidgetIds[i];

            context.startService(new Intent(context, WidgetService.class));

            Intent intent = new Intent(context, WidgetDialog.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            views.setOnClickPendingIntent(R.id.layout_widget, pendingIntent);

            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    @Override
    public void onEnabled(Context context){
        context.startService(new Intent(context, WidgetService.class));
    }

    @Override
    public void onDisabled(Context context){
        context.stopService(new Intent(context, WidgetService.class));
    }

1条回答
Melony?
2楼-- · 2019-02-11 03:46

After reboot you OnEnabled is called instead of onUpdate so move the code from onUpdate into a separate method and then call that method to update all widgets from onEnabled

查看更多
登录 后发表回答