sg.edu.nus.tasklaundrette.ChatMessagingService.java Source code

Java tutorial

Introduction

Here is the source code for sg.edu.nus.tasklaundrette.ChatMessagingService.java

Source

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package sg.edu.nus.tasklaundrette;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.CarExtender;
import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.RemoteInput;

public class ChatMessagingService extends Service {
    private static final String TAG = ChatMessagingService.class.getSimpleName();

    public static final String READ_ACTION = "sg.edu.nus.tasklaundrette.ACTION_MESSAGE_READ";
    public static final String REPLY_ACTION = "sg.edu.nus.tasklaundrette.ACTION_MESSAGE_REPLY";
    public static final String BROACT_ACTION = "sg.edu.nus.tasklaundrette.ACTION_BROADCAST_CHAT";
    public static final String CONVERSATION_ID = "conversation_id";
    public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";

    private NotificationManagerCompat mNotificationManager;

    private final Messenger mMessenger = new Messenger(new IncomingHandler());

    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Bundle data = msg.getData();
            sendNotification(data.getInt("conversation_id"), data.getString("message"),
                    data.getString("participant"), System.currentTimeMillis());
        }
    }

    @Override
    public void onCreate() {
        mNotificationManager = NotificationManagerCompat.from(getApplicationContext());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String data = intent.getStringExtra("data_info");

        try {
            Bundle args = Converter.convertToMessageData(data);
            Message msg = new Message();
            msg.setData(args);

            mMessenger.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    private Intent createIntent(int conversationId, String action) {
        return new Intent().addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES).setAction(action)
                .putExtra(CONVERSATION_ID, conversationId);
    }

    private void sendNotification(int conversationId, String message, String participant, long timestamp) {
        // A pending Intent for reads
        PendingIntent readPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
                createIntent(conversationId, READ_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);

        // Build a RemoteInput for receiving voice input in a Car Notification
        RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("Reply by voice").build();

        // Building a Pending Intent for the reply action to trigger
        PendingIntent replyIntent = PendingIntent.getBroadcast(getApplicationContext(), conversationId,
                createIntent(conversationId, REPLY_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);

        // Create the UnreadConversation and populate it with the participant name,
        // read and reply intents.
        UnreadConversation.Builder unreadConvBuilder = new UnreadConversation.Builder(participant)
                .setLatestTimestamp(timestamp).setReadPendingIntent(readPendingIntent)
                .setReplyAction(replyIntent, remoteInput);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                // Set the application notification icon:
                .setSmallIcon(R.drawable.notification_icon)
                // Set the large icon, for example a picture of the other recipient of the message
                .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(),
                        R.drawable.laundry_icon))
                .setContentText(message).setWhen(timestamp).setContentTitle(participant)
                .setContentIntent(readPendingIntent)
                .extend(new CarExtender().setUnreadConversation(unreadConvBuilder.build()))
                .setColor(getApplicationContext().getResources().getColor(R.color.light_green));

        mNotificationManager.notify(conversationId, builder.build());
    }
}