Внедрить запрос Json в локальных уведомлениях Flutter - PullRequest
0 голосов
/ 02 августа 2020

Я модифицирую библиотеку flutter flutter_local_notifications , чтобы уведомление отправлялось, как только на сервере, к которому подключено приложение, появляются новости. Плагин настроен на уведомление каждую минуту. В файле FlutterLocalNotificationsPlugin (, который вы найдете здесь ) я вставил функцию getNotify, которая с помощью preferenceOk () изменяет SharedPreferences notifyJsonOk на true.

public static void getNotify(Context context){
    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");

                if (success){

                    Object dataOb = jsonResponse;
                    JSONArray arraydata = jsonResponse.optJSONArray("data");

                    count = jsonResponse.getInt("count");

                    if (count > 0) {
                        preferenceOk();
                    } 

                } else {
                    String serviceEr = jsonResponse.getString("error");

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


            }
        }
    };
    NotifyRequest notifyRequest = new NotifyRequest(String.valueOf(userid), authkey, responseListener);
    RequestQueue queue = Volley.newRequestQueue(context);
    queue.add(notifyRequest);
}

public static void preferenceOk(){
    sharedpreferences = context.getSharedPreferences("FlutterSharedPreferences", 0);
    SharedPreferences.Editor editOk = sharedpreferences.edit();
    editOk.putBoolean("notifyJsonOk", true);
    editOk.commit();
}

Теперь я изменил метод showNotification, чтобы что он отправляет уведомление только в том случае, если есть новости с сервера.

static void showNotification(Context context, NotificationDetails notificationDetails) {
    //getNotify(context);

    sharedpreferences = context.getSharedPreferences("FlutterSharedPreferences", 0);
    boolean notifyJsonOk =  sharedpreferences.getBoolean( "notifyJsonOk", false);

    if(notifyJsonOk) {
        Notification notification = createNotification(context, notificationDetails);
        NotificationManagerCompat notificationManagerCompat = getNotificationManager(context);
        notificationManagerCompat.notify(notificationDetails.id, notification);
    }

    SharedPreferences.Editor editOk = sharedpreferences.edit();
    editOk.putBoolean("notifyJsonOk", false);
    editOk.commit();

}

Код работает, но отправляет уведомление через минуту, а не тогда, когда он фактически читает файл json сервера. Похоже, что SharedPreferences читается в следующем цикле.

...