Почему setOnClickPendingIntent не работает? - PullRequest
0 голосов
/ 15 марта 2019

Я присоединяю ожидающее намерение к кнопке виджета через .setOnClickPendingIntent и не получаю от нее ответа при нажатии кнопки.Как ни странно, когда я внедряю этот же код в свой сервис загрузки, он хочет работать (но не будет, потому что сервис работает в цикле в течение нескольких циклов, поэтому активность просто всплывает и снова исчезает при нажатии кнопки).

Мне нужно, чтобы это можно было запускать в моем главном потоке, но невозможно на всю жизнь, если я пойму, почему он не вызывает, как ожидалось.

Слушатель подключен к кнопке RemoteViews вметод ниже:

public static void updateWidget(Context context, AppWidgetManager appWidgetManager, int widgetId) {
    mContext = context;

    RemoteViews widgetViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

    // Create a PendingIntent to open the config activity
    Intent configIntent = new Intent(context, ConfigActivity.class);
    configIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
    configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);

    // Keep in mind PendingIntent uniqueness rules. Use the widget ID as a request code
    PendingIntent configPendingIntent = PendingIntent.getActivity(context, widgetId, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Attach the PendingIntent to our config button
    widgetViews.setOnClickPendingIntent(R.id.configButton, configPendingIntent);

    appWidgetManager.updateAppWidget(widgetId, widgetViews);

    if(loadChached() != null) {
        Weather weather = loadChached();

        widgetViews.setTextViewText(R.id.conditionsDisplay, weather.getConditions());
        widgetViews.setTextViewText(R.id.tempDisplay, String.valueOf(weather.getDisplayTemp()));
        widgetViews.setTextViewText(R.id.timestampDisplay, weather.getTimeStamp());

        if(loadPreferences(context).equals("Dark")) {
            Log.i(TAG, "updateWidget: Activating Dark Theme");
            widgetViews.setTextColor(R.id.conditionsDisplay, context.getResources().getColor(android.R.color.background_dark));
            widgetViews.setTextColor(R.id.tempDisplay, context.getResources().getColor(android.R.color.background_dark));
            widgetViews.setTextColor(R.id.timestampDisplay, context.getResources().getColor(android.R.color.background_dark));
        }

        else if(loadPreferences(context).equals("Light")) {
            Log.i(TAG, "updateWidget: Activating Light Theme");
            widgetViews.setTextColor(R.id.conditionsDisplay, context.getResources().getColor(android.R.color.white));
            widgetViews.setTextColor(R.id.tempDisplay, context.getResources().getColor(android.R.color.white));
            widgetViews.setTextColor(R.id.timestampDisplay, context.getResources().getColor(android.R.color.white));
        }

        appWidgetManager.updateAppWidget(widgetId, widgetViews);
    }

    Intent updateIntent = new Intent(context, DownloadIntentService.class);
    updateIntent.setAction(WeatherWidgetProvider.ACTION_UPDATE_WEATHER);

    Log.i(TAG, "onUpdate: Starting Service");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        try {
            context.startForegroundService(updateIntent);
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }

    else {
        try {
            context.startService(updateIntent);
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Активность, которую я хочу запустить, зарегистрирована в манифесте с фильтром намерений:

<activity android:name=".ConfigActivity">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
        </intent-filter>
    </activity>

Любая помощь очень ценится.

1 Ответ

0 голосов
/ 17 марта 2019

Проблема заключалась в том, что я также вызывал .updateWidget из сервиса, переопределяя все, что было добавлено к нему в провайдере. Как только я переместил все обновления обратно в главный поток, проблема была решена.

...