Два push-уведомления не отображаются - PullRequest
0 голосов
/ 07 октября 2018

Я сейчас пытаюсь отправить уведомление в моем приложении.у меня есть 2 AsyncTask с уведомлением в нем, но когда выполнить оба два в моем журнале во втором только показывает, но когда я комментирую второй, первый показывает, я знаю, что мой API работает нормально

Первая asyntask:

public class backWorkerNotifTom extends AsyncTask<String,String,String> {
Context context;
String result;
String[] BookTittle;
    public  backWorkerNotifTom(Context context){this.context = context;}
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String NotifTomURL = "http://192.168.254.120/LibrayAPI/SelectNotifTom.php";
        if (type.equals("SelectNotifTom")){
            String dateTom = params[1];
            String borrowerID = params[2];

            try {
                String data = URLEncoder.encode("date_tom","UTF-8") + "=" +
                        URLEncoder.encode(dateTom,"UTF-8");
                data += "&" + URLEncoder.encode("borrower_id","UTF-8") + "=" +
                        URLEncoder.encode(borrowerID,"UTF-8");

                URL url = new URL(NotifTomURL);
                URLConnection urlConnection = url.openConnection();
                urlConnection.setDoOutput(true);

                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
                outputStreamWriter.write(data);
                outputStreamWriter.flush();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

                StringBuilder sb = new StringBuilder();
                String line;

                while ((line = bufferedReader.readLine())!= null){
                    sb.append(line+"\n");
                }
                result = sb.toString();

                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject;
                BookTittle = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObject = jsonArray.getJSONObject(i);
                    BookTittle[i] = jsonObject.getString("BookTittle");
                    // PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, NotifList.class), 0);
                    NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_book_black_24dp)
                            .setContentTitle("Library Alert")
                            .setContentText("Tommorow is the Due Day of the Book " + BookTittle[i] + " You Borrowed")

                            //.setContentIntent(pendingIntent)
                            .setTicker("Notifications");

                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

                    if (notificationManager != null) {
                        notificationManager.notify(i, mbuilder.build());
                    }
                }
            }
            catch (Exception ex){
                ex.printStackTrace();

            }


        }
        return result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

    }
}

Вторая Asyntask:

public class backWorkerNotif extends AsyncTask<String, String, String> {
    String result = null;
    String[] BookTittle;
   Context context;
   public  backWorkerNotif(Context context){this.context = context;}

    @Override
    protected String doInBackground(String... params) {
        String selectNotif_url = "http://192.168.254.120/LibrayAPI/SelectNotif.php";
        String type = params[0];

        if (type.equals("Notif")) {
            String DateNow = params[1];
            String BorrowerID = params[2];
            try {

                String data = URLEncoder.encode("date_now", "UTF-8") + "=" +
                        URLEncoder.encode(DateNow, "UTF-8");
                data += "&" + URLEncoder.encode("borrower_id", "UTF-8") + "=" +
                        URLEncoder.encode(BorrowerID, "UTF-8");

                URL url = new URL(selectNotif_url);
                URLConnection urlConnection = url.openConnection();
                urlConnection.setDoOutput(true);

                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

                outputStreamWriter.write(data);
                outputStreamWriter.flush();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {

                    sb.append(line + "\n");
                }
                result = sb.toString();
                if (result.isEmpty()) {
                } else {
                    //Json

                    JSONArray jsonArray = new JSONArray(result);
                    JSONObject jsonObject;
                    BookTittle = new String[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        jsonObject = jsonArray.getJSONObject(i);
                        BookTittle[i] = jsonObject.getString("BookTittle");
                       // PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, NotifList.class), 0);
                        NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(R.drawable.ic_book_black_24dp)
                                .setContentTitle("Library notification")
                                .setContentText("Today is the Due Day of the Book " + BookTittle[i] + " You Borrowed")

                                //.setContentIntent(pendingIntent)
                                .setTicker("Notification Alert");

                        NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

                        if (notificationManager != null) {
                            notificationManager.notify(i, mbuilder.build());
                        }
                    }
                }
            }
            catch (Exception ex) {
                ex.printStackTrace();

            }


        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String jsonArray) {
        super.onPostExecute(jsonArray);

    }
}

Войти в класс

public class Login extends AppCompatActivity {

    EditText username,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = findViewById(R.id.edtUsername);
        password = findViewById(R.id.edtPassword);
    }

    public void onLogin(View view) {

        String Username = username.getText().toString();
        String Password = password.getText().toString();
        //notif call
        //call notif for overdue tommorow
        backWorkerNotifTom backWorkerNotifTom = new backWorkerNotifTom(this);
      //get datetime tom
       Calendar calendar =  Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,1);
        Date dateTom = calendar.getTime();
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateTomString = sf1.format(dateTom);
        Toast.makeText(this, dateTomString, Toast.LENGTH_SHORT).show();
        backWorkerNotifTom.execute("SelectNotifTom",dateTomString,Username);

        backWorkerNotif backWorkerNotif = new backWorkerNotif(this);
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd");
        String DateNow = SF.format(date);
        backWorkerNotif.execute("Notif", DateNow, Username);

        String Type = "login";
        GlobalVariable.BorrowerID = Username;
        GlobalVariable.Password = Password;
        backgroundWorker _backgroundWorker = new backgroundWorker(this);
        _backgroundWorker.execute(Type, Username, Password);


    }
}

1 Ответ

0 голосов
/ 07 октября 2018

Это, вероятно, происходит потому, что вы используете одинаковые идентификаторы при создании обоих типов уведомлений.Это заставит второй перезаписать первый.Если вы хотите показать несколько уведомлений, каждому из них потребуется отдельный идентификатор.

Проблемная строка кода - notificationManager.notify(i, mbuilder.build()); в обеих асинхронных задачах.Поскольку 'i' создается как int в диапазоне от 0 массива, вы получаете много конфликтов между двумя задачами.Вы должны убедиться, что каждое уведомление использует уникальный идентификатор

...