提供后台服务以使用socket.io显示通知

时间:2018-12-31 19:07:33

标签: android socket.io

我正在开发android聊天应用程序。首先,我使用nodejs创建socket.io服务器。然后从android我连接到服务器。我的最后一个任务是创建服务,以在前台应用程序时显示通知。

我创建这样的服务:

public class BService extends Service {
public Socket mSocket;
public BService that = this;
Context ctx;
public static boolean isServiceRunning = false;
InfoSharedPreferences userInfoSharedP;                                    public BService() {
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    userInfoSharedP = new InfoSharedPreferences(getApplicationContext());
    try {
        IO.Options opts = new IO.Options();
        opts.secure = true;
        opts.transports = new String[]{WebSocket.NAME};
        opts.reconnection = true;
        opts.forceNew = true;

        mSocket = IO.socket("url",opts);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    mSocket.on(Socket.EVENT_CONNECT,onConnect);
    mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
    mSocket.on("userInbox", userInbox);
    mSocket.connect();
    return START_STICKY;
}

@Override
public void onCreate() {
    ctx = getApplicationContext();
}

private void createNotification(String title,String text) {
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
        Objects.requireNonNull(notificationManager).createNotificationChannel(notificationChannel);
        builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
    } else {
        builder = new NotificationCompat.Builder(getApplicationContext());
    }

    builder = builder
            .setSmallIcon(R.drawable.logotext)
            .setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.logo))
            .setContentTitle(title)
            .setTicker(ctx.getString(R.string.newmessage))
            .setContentText(text)
            .setWhen(System.currentTimeMillis())
            .setDefaults(Notification.DEFAULT_ALL)
            .setAutoCancel(true);

    Intent resultIntent = new Intent(this, ChatBoxActivity.class);

    android.support.v4.app.TaskStackBuilder stackBuilder = android.support.v4.app.TaskStackBuilder.create(this);
    stackBuilder.addParentStack(ChatBoxActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT );
    builder.setContentIntent(resultPendingIntent);

    if (notificationManager != null) {
        int mId = 9910;
        notificationManager.notify(mId, builder.build());
    }
}


private Emitter.Listener userInbox = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        JSONObject data = (JSONObject) args[0];
        try {
            String message = data.getString("message");
            createNotification(ctx.getString(R.string.newmessage),message);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
};

private Emitter.Listener onConnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
               mSocket.emit("join", userInfoSharedP.getUserId());
            }
};

private Emitter.Listener onDisconnect = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        if(!mSocket.connected())mSocket.connect();
    }
};


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

@Override
public void onDestroy() {
    super.onDestroy();
    isServiceRunning = false;
    mSocket.emit("manual-disconnection", userInfoSharedP.getUserId()); 
    mSocket.disconnect();
    mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
    mSocket.off("userInbox", userInbox);
    mSocket.close();
}}

一切正常,直到用户未将应用程序杀死在进程托盘中。

即使应用程序被杀死,我如何创建服务以显示通知并保持Socket IO连接保持活动状态?

或者如何通过FCM + socket io服务做到这一点?

0 个答案:

没有答案