Android Widget按钮onClickPendingIntent在睡眠后无法正常工作

时间:2015-04-06 09:14:33

标签: android android-intent android-widget android-appwidget

我正在学习根据https://looksok.wordpress.com/2012/12/15/android-complete-widget-tutorial-including-source-code/

的教程创建Android小部件

我修改了它,以便小部件包含2个intent,一个用于widget_button,另一个用于widget_image。当新添加小部件时,两个意图都在工作。但是,在我让手机进入睡眠状态较长时间后,只有widget_image的意图正在工作,而widget_button的意图却没有。如果我打开我的应用程序MainActivity,widget_button的意图将恢复正常工作。

这是widgetprovider类:

public class MyWidgetProvider extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

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

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo);
        remoteViews.setOnClickPendingIntent(R.id.widget_button, buildButtonPendingIntent(context));

        remoteViews.setOnClickPendingIntent(R.id.widget_image, pendingIntent);

        pushWidgetUpdate(context, remoteViews);
}

public static PendingIntent buildButtonPendingIntent(Context context) {
    Intent intent = new Intent();
    intent.setAction("com.example.intent.action.CHANGE_PICTURE");
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
    ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(myWidget, remoteViews);
}

}

这是接收器类:

public class MyWidgetIntentReceiver extends BroadcastReceiver {

private static int clickCount = 0;

@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals("com.example.intent.action.CHANGE_PICTURE")){
        updateWidgetPictureAndButtonListener(context);
    }
}

private void updateWidgetPictureAndButtonListener(Context context) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo);
    remoteViews.setImageViewResource(R.id.widget_image, getImageToSet());

    //REMEMBER TO ALWAYS REFRESH YOUR BUTTON CLICK LISTENERS!!!
    remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context));

    MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews);
}

private int getImageToSet() {

    clickCount++;
    if (clickCount == 1) {
        return R.drawable.image1 ;
    }
    if (clickCount == 2) {
        return R.drawable.image2 ;
    }
    if (clickCount == 3) {
        return R.drawable.image3 ;
    }
    clickCount = 0;
    return R.drawable.image4 ;
}

}

如何解决这个问题?

0 个答案:

没有答案