Android Open Source - matrix-android-sdk Event Stream Service






From Project

Back to project page matrix-android-sdk.

License

The source code is released under:

Apache License

If you think the Android project matrix-android-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package org.matrix.matrixandroidsdk.services;
//  w  w w  .j a va 2 s .c  o  m
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.matrixandroidsdk.activity.HomeActivity;
import org.matrix.matrixandroidsdk.Matrix;
import org.matrix.matrixandroidsdk.R;
import org.matrix.matrixandroidsdk.activity.RoomActivity;
import org.matrix.matrixandroidsdk.util.EventUtils;

/**
 * A foreground service in charge of controlling whether the event stream is running or not.
 */
public class EventStreamService extends Service {
    public static enum StreamAction {
        UNKNOWN,
        STOP,
        START,
        PAUSE,
        RESUME
    }
    public static final String EXTRA_STREAM_ACTION = "org.matrix.matrixandroidsdk.services.EventStreamService.EXTRA_STREAM_ACTION";

    private static final String LOG_TAG = "EventStreamService";
    private static final int NOTIFICATION_ID = 42;
    private static final int MSG_NOTIFICATION_ID = 43;

    private MXSession mSession;
    private StreamAction mState = StreamAction.UNKNOWN;

    private MXEventListener mListener = new MXEventListener() {
        @Override
        public void onLiveEvent(Event event, RoomState roomState) {
            if (EventUtils.shouldNotify(EventStreamService.this, event)) {
                String from = event.userId;
                String body = event.content.getAsJsonPrimitive("body").getAsString();
                Notification n = buildMessageNotification(from, body, event.roomId);
                NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE);
                Log.w(LOG_TAG, "onMessageEvent >>>> " + event);
                nm.notify(MSG_NOTIFICATION_ID, n);
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        StreamAction action = StreamAction.values()[intent.getIntExtra(EXTRA_STREAM_ACTION, StreamAction.UNKNOWN.ordinal())];
        Log.d(LOG_TAG, "onStartCommand >> "+action);
        switch (action) {
            case START:
            case RESUME:
                start();
                break;
            case STOP:
                stop();
                break;
            case PAUSE:
                pause();
                break;
            default:
                break;
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        stop();
    }

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

    private void start() {
        if (mState == StreamAction.START) {
            Log.w(LOG_TAG, "Already started.");
            return;
        }
        else if (mState == StreamAction.PAUSE) {
            Log.i(LOG_TAG, "Resuming active stream.");
            resume();
            return;
        }
        if (mSession == null) {
            mSession = Matrix.getInstance(getApplicationContext()).getDefaultSession();
            if (mSession == null) {
                Log.e(LOG_TAG, "No valid MXSession.");
                return;
            }
        }

        mSession.getDataHandler().addListener(mListener);
        mSession.startEventStream();
        startWithNotification();
    }

    private void stop() {
        stopForeground(true);
        if (mSession != null) {
            mSession.stopEventStream();
            mSession.getDataHandler().removeListener(mListener);
        }
        mSession = null;
        mState = StreamAction.STOP;
    }

    private void pause() {
        stopForeground(true);
        if (mSession != null) {
            mSession.pauseEventStream();
        }
        mState = StreamAction.PAUSE;
    }

    private void resume() {
        if (mSession != null) {
            mSession.resumeEventStream();
        }
        startWithNotification();
    }

    private void startWithNotification() {
        Notification notification = buildNotification();
        startForeground(NOTIFICATION_ID, notification);
        mState = StreamAction.START;
    }

    private Notification buildMessageNotification(String from, String body, String roomId) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setWhen(System.currentTimeMillis());
        builder.setContentTitle(from + " (Matrix)");
        builder.setContentText(body);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_menu_start_conversation);

        // Build the pending intent for when the notification is clicked
        Intent roomIntent = new Intent(this, RoomActivity.class);
        roomIntent.putExtra(RoomActivity.EXTRA_ROOM_ID, roomId);
        // Recreate the back stack
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this)
                .addParentStack(RoomActivity.class)
                .addNextIntent(roomIntent);

        builder.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

        Notification n = builder.build();
        n.flags |= Notification.FLAG_SHOW_LIGHTS;
        n.defaults |= Notification.DEFAULT_LIGHTS;
//        n.defaults |= Notification.DEFAULT_VIBRATE;
        return n;
    }

    private Notification buildNotification() {
        Notification notification = new Notification(
                R.drawable.ic_menu_start_conversation,
                "Matrix",
                System.currentTimeMillis()
        );

        // go to the home screen if this is clicked.
        Intent i = new Intent(this, HomeActivity.class);

        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);

        notification.setLatestEventInfo(this, getString(R.string.app_name),
                "Listening for events",
                pi);
        notification.flags |= Notification.FLAG_NO_CLEAR;
        return notification;
    }
}




Java Source Code List

org.matrix.androidsdk.MXDataHandler.java
org.matrix.androidsdk.MXSession.java
org.matrix.androidsdk.RestClient.java
org.matrix.androidsdk.data.DataRetriever.java
org.matrix.androidsdk.data.IMXStore.java
org.matrix.androidsdk.data.MXMemoryStore.java
org.matrix.androidsdk.data.MyUser.java
org.matrix.androidsdk.data.RoomState.java
org.matrix.androidsdk.data.RoomSummary.java
org.matrix.androidsdk.data.Room.java
org.matrix.androidsdk.listeners.IMXEventListener.java
org.matrix.androidsdk.listeners.MXEventListener.java
org.matrix.androidsdk.rest.api.EventsApi.java
org.matrix.androidsdk.rest.api.LoginApi.java
org.matrix.androidsdk.rest.api.PresenceApi.java
org.matrix.androidsdk.rest.api.ProfileApi.java
org.matrix.androidsdk.rest.api.RegistrationApi.java
org.matrix.androidsdk.rest.api.RoomsApi.java
org.matrix.androidsdk.rest.callback.ApiCallback.java
org.matrix.androidsdk.rest.callback.ApiFailureCallback.java
org.matrix.androidsdk.rest.callback.RestAdapterCallback.java
org.matrix.androidsdk.rest.callback.SimpleApiCallback.java
org.matrix.androidsdk.rest.client.EventsRestClient.java
org.matrix.androidsdk.rest.client.LoginRestClient.java
org.matrix.androidsdk.rest.client.PresenceRestClient.java
org.matrix.androidsdk.rest.client.ProfileRestClient.java
org.matrix.androidsdk.rest.client.RegistrationRestClient.java
org.matrix.androidsdk.rest.client.RestClientTest.java
org.matrix.androidsdk.rest.client.RoomsRestClient.java
org.matrix.androidsdk.rest.model.BannedUser.java
org.matrix.androidsdk.rest.model.ContentResponse.java
org.matrix.androidsdk.rest.model.CreateRoomResponse.java
org.matrix.androidsdk.rest.model.Event.java
org.matrix.androidsdk.rest.model.ImageInfo.java
org.matrix.androidsdk.rest.model.ImageMessage.java
org.matrix.androidsdk.rest.model.InitialSyncResponse.java
org.matrix.androidsdk.rest.model.MatrixError.java
org.matrix.androidsdk.rest.model.MessageFeedback.java
org.matrix.androidsdk.rest.model.Message.java
org.matrix.androidsdk.rest.model.PowerLevels.java
org.matrix.androidsdk.rest.model.PublicRoom.java
org.matrix.androidsdk.rest.model.RoomMember.java
org.matrix.androidsdk.rest.model.RoomResponse.java
org.matrix.androidsdk.rest.model.TextMessage.java
org.matrix.androidsdk.rest.model.TokensChunkResponse.java
org.matrix.androidsdk.rest.model.User.java
org.matrix.androidsdk.rest.model.login.Credentials.java
org.matrix.androidsdk.rest.model.login.LoginFlowResponse.java
org.matrix.androidsdk.rest.model.login.LoginFlow.java
org.matrix.androidsdk.rest.model.login.LoginParams.java
org.matrix.androidsdk.rest.model.login.PasswordLoginParams.java
org.matrix.androidsdk.sync.DefaultEventsThreadListener.java
org.matrix.androidsdk.sync.EventsThreadListener.java
org.matrix.androidsdk.sync.EventsThreadTest.java
org.matrix.androidsdk.sync.EventsThread.java
org.matrix.androidsdk.util.ContentManager.java
org.matrix.androidsdk.util.ContentUtils.java
org.matrix.androidsdk.util.JsonUtils.java
org.matrix.matrixandroidsdk.ApplicationTest.java
org.matrix.matrixandroidsdk.ErrorListener.java
org.matrix.matrixandroidsdk.Matrix.java
org.matrix.matrixandroidsdk.ViewedRoomTracker.java
org.matrix.matrixandroidsdk.activity.CommonActivityUtils.java
org.matrix.matrixandroidsdk.activity.HomeActivity.java
org.matrix.matrixandroidsdk.activity.LoginActivity.java
org.matrix.matrixandroidsdk.activity.PublicRoomsActivity.java
org.matrix.matrixandroidsdk.activity.RoomActivity.java
org.matrix.matrixandroidsdk.activity.RoomInfoActivity.java
org.matrix.matrixandroidsdk.activity.SettingsActivity.java
org.matrix.matrixandroidsdk.activity.SplashActivity.java
org.matrix.matrixandroidsdk.adapters.AdapterUtils.java
org.matrix.matrixandroidsdk.adapters.MessageRow.java
org.matrix.matrixandroidsdk.adapters.MessagesAdapter.java
org.matrix.matrixandroidsdk.adapters.RoomMembersAdapter.java
org.matrix.matrixandroidsdk.adapters.RoomSummaryAdapter.java
org.matrix.matrixandroidsdk.adapters.RoomsAdapter.java
org.matrix.matrixandroidsdk.fragments.MatrixMessageListFragment.java
org.matrix.matrixandroidsdk.fragments.MatrixMessagesFragment.java
org.matrix.matrixandroidsdk.fragments.RoomMembersDialogFragment.java
org.matrix.matrixandroidsdk.services.EventStreamService.java
org.matrix.matrixandroidsdk.store.LoginStorage.java
org.matrix.matrixandroidsdk.util.EventUtils.java
org.matrix.matrixandroidsdk.util.ResourceUtils.java
org.matrix.matrixandroidsdk.util.UIUtils.java
org.matrix.matrixandroidsdk.view.PieFractionView.java