Уведомление в чате с использованием сигнализатора только при активности чата. По крайней мере, один раз открыть работу (выполнить ChatActivity onCreate) - PullRequest
0 голосов
/ 11 марта 2019

Ниже приведен мой код. Все работает нормально, но уведомление работает только тогда, когда хотя бы раз открыт ChatActivity и приложение не закрыто. Как получать уведомления без необходимости запуска onCreate в ChatActivity каждый раз?

Активность в чате

public class ChatActivity extends AppCompatActivity {

    public static HubConnection connection = new HubConnection("http://testwebserv.tahlilgargroup.ir/");
    public static HubProxy hub = connection.createHubProxy("ChatHub");
    String msgContent;
    static String id;
    JsonArray jsonArray;
    static ChatAppMsgDTO msgDto;
    @SuppressLint("StaticFieldLeak")
    public static TextView txtStatus;
    EditText msgInputText;
    Button msgSendButton;
    RecyclerView msgRecyclerView;
    public static Handler handler;
    public static Runnable handlerTask;
    public static ServerSentEventsTransport sse;
    static List<ChatAppMsgDTO> msgDtoList;
    ChatAppMsgAdapter chatAppMsgAdapter;
    static int index;
    static int tempIndx;
    static String tempMsg = "0";
    static ArrayList<String> mess = new ArrayList<>();
    static boolean active = false;

    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            if (extras.containsKey("position")) {
                id = extras.getString("position");

            }

        }

        init();



        StartTimer();


        connection.error(new ErrorCallback() {

            @Override
            public void onError(final Throwable error) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        //txtStatus.setText("error");
                        // Toast.makeText(getApplicationContext(), "ConError: " + error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });

            }
        });


        hub.subscribe(new Object() {
            @SuppressWarnings("unused")
            public void messageReceived(final String name, final String message) {

                runOnUiThread(new `Runnable`() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), name + ": " + message, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });


        MessageRecive();


    }

MessageRecive ()

public void MessageRecive() {
    connection.received(new MessageReceivedHandler() {
        @Override
        public void onMessageReceived(final JsonElement json) {
            runOnUiThread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                public void run() {
                    JsonObject jsonObject = json.getAsJsonObject();
                    if (jsonObject != null && jsonObject.has("A")) {
                        jsonArray = jsonObject.getAsJsonArray("A");
                        if (jsonArray != null && jsonArray.size() != 0) {
                            id = jsonArray.get(2).getAsString();
                            if (jsonArray.get(2).getAsInt() == Integer.parseInt(id) && jsonArray.get(3).getAsInt() == 2) {

                                Notify();


                                msgDto = new ChatAppMsgDTO(ChatAppMsgDTO.MSG_TYPE_RECEIVED,
                                        jsonArray.get(0).getAsString(),
                                        jsonArray.get(1).getAsString(),
                                        jsonArray.get(5).getAsString());
                                msgDtoList.add(msgDto);
                                int newMsgPosition = msgDtoList.size() - 1;
                                chatAppMsgAdapter.notifyItemInserted(newMsgPosition);
                                msgRecyclerView.scrollToPosition(newMsgPosition);

                            } else if (jsonArray.get(2).getAsInt() == 2) {


                                    ChatAppMsgAdapter.Sendstate = ChatAppMsgAdapter.state.send;
                                    msgDto = new ChatAppMsgDTO(ChatAppMsgDTO.MSG_TYPE_SENT, msgContent, "", jsonArray.get(5).getAsString());

                                    msgDtoList.set(index, msgDto);
                                    chatAppMsgAdapter.notifyItemChanged(index);
                                    msgRecyclerView.scrollToPosition(index);




                                }

                            }
                        }
                    }
                }
            });
        }
    });
}

Notify ()

public void Notify() {

    if (!active) {
        final String NOTIFICATION_CHANNEL_ID = "10001";
        id = jsonArray.get(2).getAsString();

        String notification_title = jsonArray.get(1).getAsString();
        String notification_message = jsonArray.get(0).getAsString();
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.tahlil)
                        .setContentTitle(notification_title)
                        .setContentText(notification_message)
                        .setAutoCancel(true)
                        .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                        .setSound(Uri.parse("android.resource://"
                        + getApplication().getPackageName() + "/" + R.raw.sms)/* alarmSound*/);



        Intent resultIntent = new Intent(getApplicationContext(), ChatActivity.class);
        // resultIntent.putExtra("user_id", from_user_id);

        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        mBuilder.setContentIntent(resultPendingIntent);
        int mNotificationId = (int) System.currentTimeMillis();
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);

            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotifyMgr.createNotificationChannel(notificationChannel);
        }
        mNotifyMgr.notify(mNotificationId, mBuilder.build());
    }

}

Сервис для уведомлений

public class NotificationService extends Service {

    Timer timer;
    TimerTask timerTask;
    String TAG = "Timers";
    int Your_X_SECS = 5;


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);

        startTimer();

        return START_STICKY;
    }


    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");


    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        stoptimertask();
        super.onDestroy();


    }

    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();


    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 5000, Your_X_SECS * 1000); //
        //timer.schedule(timerTask, 5000,1000); //
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    public void run() {

                        //TODO CALL NOTIFICATION FUNC

                        ChatActivity m=new ChatActivity();
                        m.Notify();

                    }
                });
            }
        };
    }}

, которые запускают службу в onCreate () первого действия приложения:

startService(new Intent(this, NotificationService.class));

Пожалуйста, просмотрите мой код и оставьте отзыв.

...