Я создал виджеты, но они не загружаются правильно после перезагрузки - PullRequest
1 голос
/ 22 января 2020

Я создаю виджет из приложения. Но они не загружаются правильно после перезагрузки. На самом деле моя проблема, например, я добавил три виджета на главном экране, но иногда один или два виджета загружается, но другой виджет не загружается. Скриншот для лучшего понимания . Yükleniyor означает загрузку. Пожалуйста, помогите мне.

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {


    AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
    ComponentName widgetComponent = new ComponentName(context,MyNotesWidget.class);
    int[] appWidgetIds = widgetManager.getAppWidgetIds(widgetComponent);

    for(int i = 0; i < appWidgetIds.length; i++){
        MyNotesWidget.updateAppWidgets(context,widgetManager,appWidgetIds[i]);
    }


}
}


    //in my widget provider MyNotesWidget.class
    public static RemoteViews updateWidgetListViews(Context context, int appWidgetId) {

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_notes_widget);
    dataSource = new DataSource(context);
    dataSource.open();
    int noteId = MySharedPref.getNoteIdFromWidgetId(context,appWidgetId);

    int color = dataSource.getColor(noteId);

    remoteViews.setInt(R.id.widgetLinearLayout, "setBackgroundColor", color);

    MyNotesWidgetActivity.widgetProcess = "receive";
    Intent svcIntent = new Intent(context, WidgetViewService.class);
    svcIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_ENABLED);
    svcIntent.setData(Uri.fromParts("content", String.valueOf(noteId), null));
    remoteViews.setRemoteAdapter(R.id.listViewWidget, svcIntent);
    return remoteViews;

}

// мой сервис Widget

public class WidgetViewService extends RemoteViewsService {

@Override
public RemoteViewsService.RemoteViewsFactory onGetViewFactory(Intent intent) {

      return (new WidgetListProvider(this.getApplicationContext(), intent));
}

}

public class WidgetListProvider implements RemoteViewsService.RemoteViewsFactory {

private Context context;
private int appWidgetId;
private MySharedPref mySharedPref;

private int noteId;
private int widgetId;
private int size = 1;
private AppWidgetManager appWidgetManager;





public WidgetListProvider(Context context, Intent intent) {

    this.appWidgetManager = AppWidgetManager.getInstance(context);
    this.context = context;
    this.noteId = Integer.valueOf(intent.getData().getSchemeSpecificPart());

    if (0 != MyNotesWidgetActivity.widgetProcess.compareTo("create")) {
        this.widgetId = intent.getIntExtra("widgetId", 0);
    }


}

@Override
public int getCount() {
    return size;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public RemoteViews getViewAt(int position) {

    String content;
    String title;
    String date;
    String category;
    int color;
    final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.list_row);

    DataSource db = new DataSource(context);

    db.open();

        title = db.getTitle(noteId);
        content = db.getNote(noteId);
        date = db.getNoteDate(noteId);
        category = db.getCategory(noteId);
         color = db.getColor(noteId);



    remoteView.setTextViewText(R.id.title, title);
    remoteView.setTextViewText(R.id.content, content);
    remoteView.setTextViewText(R.id.date, date);
    remoteView.setTextViewText(R.id.category, category);

    if (isColorDark(color)) {
        remoteView.setInt(R.id.title, "setTextColor", Color.WHITE);
        remoteView.setInt(R.id.content, "setTextColor", Color.WHITE);

        remoteView.setInt(R.id.date, "setTextColor", Color.WHITE);
        remoteView.setInt(R.id.category, "setTextColor", Color.WHITE);
    } else {
        remoteView.setInt(R.id.title, "setTextColor", Color.BLACK);
        remoteView.setInt(R.id.content, "setTextColor", Color.BLACK);

        remoteView.setInt(R.id.date, "setTextColor", Color.BLACK);
        remoteView.setInt(R.id.category, "setTextColor", Color.BLACK);
    }


    if (0 != MyNotesWidgetActivity.widgetProcess.compareTo("create")) {
        appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.content);
    }
    return remoteView;
}


@Override
public RemoteViews getLoadingView() {
    return null;
}

@Override
public int getViewTypeCount() {
    return 1;
}

@Override
public boolean hasStableIds() {
    return true;
}

@Override
public void onCreate() {
}

@Override
public void onDataSetChanged() {


}

@Override
public void onDestroy() {
}


private boolean isColorDark(int color) {
    double darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255;
    if (darkness < 0.2) {
        return false; // It's a light color
    } else {
        return true; // It's a dark color
    }
}

}

Из моего файла манифеста:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <receiver
        android:name=".MyReceiver"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="com.comradesoftware54.mynotess.boot" />

        </intent-filter>
    </receiver>


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

        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/my_notes_widget_info" />
    </receiver>

  <service
        android:enabled="true"
        android:exported="false"
        android:name=".WidgetViewService"
        android:permission="android.permission.BIND_REMOTEVIEWS" />

My Info Widget info file :

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:configure="com.comradesoftware54.mynotess.MyNotesWidgetActivity"
android:initialKeyguardLayout="@layout/my_notes_widget"
android:initialLayout="@layout/my_notes_widget"
android:minWidth="110dp"
android:minHeight="110dp"
android:previewImage="@drawable/mynotes_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="86400000"
android:widgetCategory="home_screen|keyguard" />

1 Ответ

0 голосов
/ 22 января 2020

это так странно, но я добавил эти две строки в мой приемник. меня устраивает. :) Я надеюсь, что это работает для других друзей.

  <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
  <category android:name="android.intent.category.DEFAULT"/>



   <receiver
        android:name=".MyReceiver"
        android:enabled="true"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="com.comradesoftware54.mynotess.boot" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

Это сработало, но затем виджеты исчезли. На этот раз я добавил, что

android:installLocation="internalOnly"


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.comradesoftware54.mynotess"
android:installLocation="internalOnly">

Мне это помогло. Удачи: D

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...