OneSignal通知问题

时间:2018-12-30 18:03:20

标签: android onesignal

我正在尝试第一次在我的App中向特定的人发送通知。

我发送了,其他人应按“确认”。这个过程是 成功,但是第二次我将其发送给同一个人时,它假定他在按下之前先按下“确认”,然后进入if正文...

我想知道为什么会这样。
我该怎么办?

这是我的代码:

class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler 
{
    // This fires when a notification is opened by tapping on it.
    DatabaseReference myref,appointmentRef;
    FirebaseUser user;
    static Appointments point;
    private Application application;

    public ExampleNotificationOpenedHandler(Application application) {
        this.application = application;
    }

    @Override
    public void notificationOpened(final OSNotificationOpenResult result) {

        OSNotificationAction.ActionType actionType = result.action.type;
        JSONObject data = result.notification.payload.additionalData;
        String customKey;
        String msg = result.notification.payload.body;


        if (data != null) {
            customKey = data.optString("customkey", null);
            if (customKey != null)
                Log.i("OneSignalExample", "customkey set with value: " + customKey);
        }
        if (msg.equals("visit have been ended!")) {
            Intent intent = new Intent(application, RatingProvider.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            application.startActivity(intent);
        } else if (result.action.actionID == null)
            startApp();


        if (actionType == OSNotificationAction.ActionType.ActionTaken)
            Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);


        if (result.action.actionID.equals("confirmBtn"))
        {
            user = FirebaseAuth.getInstance().getCurrentUser();
            Log.i("abcd", "notificationOpened:bla bla ");
            myref = FirebaseDatabase.getInstance().getReference("TempAppointments");
            myref.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot)
                {
                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        point = postSnapshot.getValue(Appointments.class);
                        if (point.getProviderID().equals(user.getUid())) {
                            FirebaseDatabase datab = FirebaseDatabase.getInstance();
                            DatabaseReference Ref = datab.getReference("Appointments");
                            String[] timeParts, dateParts;
                            String year, month, day;
                            dateParts = point.getDate().split("/");
                            timeParts = point.getTime().split(":");
                            day = dateParts[2];
                            year = dateParts[0];
                            month = dateParts[1];
                            String hour = timeParts[0];
                            String minute = timeParts[1];
                            Ref.child(point.getProviderID() + point.getPatientID() + year + month + day + hour + minute).setValue(point);
                            Intent intent = new Intent(application, SignIn.class);
                           intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                            application.startActivity(intent);
                            String msg = point.getProvName() + " have been confirmed the appointment";
                            user = FirebaseAuth.getInstance().getCurrentUser();
                            String send_email = point.getPatientID();
                            String strJsonBody = "{"
                                    + "\"app_id\": \"f0d1c236-2c10-40c5-8990-28a903e05a0b\","
                                    + "\"filters\": [{\"field\": \"tag\", \"key\": \"User_ID\", \"relation\": \"=\", \"value\": \"" + send_email + "\"}],"
                                    + "\"data\": {\"foo\": \"bar\"},"
                                    + "\"contents\": {\"en\": \"" + msg + "\"},"
                                    + "\"headings\": {\"en\": \"New Request\", \"es\": \"Spanish Subtitle\"}"
                                    + "}";
                            sendNotification(strJsonBody);
                            result.action.actionID = null;


                            myref.child(point.getProviderID() + point.getPatientID() + year + month + day + hour + minute).setValue(null);
                            break;

                        }
                    }
                    result.action.actionID = null;
                    appointmentRef = FirebaseDatabase.getInstance().getReference("Appointments");
                    appointmentRef.addChildEventListener(new ChildEventListener() {
                        @Override
                        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                            user = FirebaseAuth.getInstance().getCurrentUser();
                            Appointments app = dataSnapshot.getValue(Appointments.class);
                            if (app.getProviderID().equals(user.getUid()) || app.getPatientID().equals(user.getUid())) {
                                String[] timeParts = app.getTime().split(":");
                                String hour0 = timeParts[0];
                                int hour = Integer.parseInt(hour0);
                                String minute0 = timeParts[1];
                                int minute = Integer.parseInt(minute0);
                                String[] dateParts = app.getDate().split("/");
                                String day0 = dateParts[2];
                                int day = Integer.parseInt(day0);
                                String year0 = dateParts[0];
                                int year = Integer.parseInt(year0);
                                String month0 = dateParts[1];
                                int month = Integer.parseInt(month0);
                                Calendar beginTime = Calendar.getInstance();
                                beginTime.set(year, month - 1, day, hour, minute);
                                Calendar endTime = Calendar.getInstance();
                                endTime.set(year, month - 1, day, hour + 1, minute);
                                Intent intent = new Intent(Intent.ACTION_INSERT)
                                        .setData(CalendarContract.Events.CONTENT_URI)
                                        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
                                        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
                                        .putExtra(CalendarContract.Events.TITLE, "you have an appointment")
                                        .putExtra(CalendarContract.Events.DESCRIPTION, "appointment")
                                        .putExtra(CalendarContract.Events.EVENT_LOCATION, app.getPate_location())
                                        .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
                                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                                application.startActivity(intent);
                            }
                        }

                        @Override
                        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
                        @Override
                        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { }
                        @Override
                        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) { }
                    });
                }

                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.w("", "Failed to read value.", error.toException());
                }
            });

            result.action.actionID = null;
        } else if (result.action.actionID != null && result.action.actionID.equals("declineBtn"))
        {
            user = FirebaseAuth.getInstance().getCurrentUser();
            myref = FirebaseDatabase.getInstance().getReference("TempAppointments");
            myref.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        point = postSnapshot.getValue(Appointments.class);
                        if (point.getProviderID().equals(user.getUid())) {
                            String[] timeParts, dateParts;
                            String year, month, day;
                            dateParts = point.getDate().split("/");
                            timeParts = point.getTime().split(":");
                            day = dateParts[2];
                            year = dateParts[0];
                            month = dateParts[1];
                            String hour = timeParts[0];
                            String minute = timeParts[1];
                            myref.child(point.getProviderID() + point.getPatientID() + year + month + day + hour + minute).setValue(null);
                            String msg = point.getProvName() + " is not available at that time!";
                            String send_email = point.getPatientID();
                            String strJsonBody = "{"
                                    + "\"app_id\": \"f0d1c236-2c10-40c5-8990-28a903e05a0b\","
                                    + "\"filters\": [{\"field\": \"tag\", \"key\": \"User_ID\", \"relation\": \"=\", \"value\": \"" + send_email + "\"}],"
                                    + "\"data\": {\"foo\": \"bar\"},"
                                    + "\"contents\": {\"en\": \"" + msg + "\"},"
                                    + "\"headings\": {\"en\": \"New Request\", \"es\": \"Spanish Subtitle\"}"

                                    + "}";
                            sendNotification(strJsonBody);
                            break;
                        }
                    }

                }


                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

            result.action.actionID = null;

        }
        // startApp();
        result.action.actionID = null;

    }

    // The following can be used to open an Activity of your choice.
    // Replace - getApplicationContext() - with any Android Context.
    private void startApp() {

        Intent intent = new Intent(application, SignIn.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        application.startActivity(intent);
    }

    private void sendNotification(final String str) {
        user = FirebaseAuth.getInstance().getCurrentUser();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                int SDK_INT = android.os.Build.VERSION.SDK_INT;
                if (SDK_INT > 8) {
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                            .permitAll().build();
                    StrictMode.setThreadPolicy(policy);


                    try {
                        String jsonResponse;

                        URL url = new URL("https://onesignal.com/api/v1/notifications");
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setUseCaches(false);
                        con.setDoOutput(true);
                        con.setDoInput(true);

                        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                        con.setRequestProperty("Authorization", "Basic OGUzYWYzMTItZjI1NC00ODk2LTllMzEtOTMyODZlMmEzYTg1");
                        con.setRequestMethod("POST");
                        String strJsonBody = str;
                        System.out.println("strJsonBody:\n" + strJsonBody);

                        byte[] sendBytes = strJsonBody.getBytes("UTF-8");
                        con.setFixedLengthStreamingMode(sendBytes.length);

                        OutputStream outputStream = con.getOutputStream();
                        outputStream.write(sendBytes);

                        int httpResponse = con.getResponseCode();
                        System.out.println("httpResponse: " + httpResponse);

                        if (httpResponse >= HttpURLConnection.HTTP_OK
                                && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
                            Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
                            jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                            scanner.close();
                        } else {
                            Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
                            jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                            scanner.close();
                        }
                        System.out.println("jsonResponse:\n" + jsonResponse);

                    } catch (Throwable t) {
                        t.printStackTrace();
                    }    
                }
            }
        });    
    }    
}

0 个答案:

没有答案