【问题标题】:Socket Io With Android Service带有 Android 服务的 Socket Io
【发布时间】:2017-07-01 22:27:56
【问题描述】:

美好的一天。考虑到适用于 android 的 Socket IO 库及其服务,我有一个非常具体的问题。

重要的是要提到我的设备是我正在测试的华为 p8 lite。

来了:

• 我有一个套接字 Io 库,它正在我创建的服务中初始化

• 我将侦听器设置为新消息的套接字 io

• 如果应用程序没有在进程树中被用户杀死,那么一切都像 char 一样工作。

• 服务的目的是让套接字 IO 连接保持活动状态,即使应用程序被终止,用户也会收到有关新消息的通知。

• 一旦应用程序被杀死,Socket IO 连接就被断开了

无论我尝试什么,我都会尝试所有可能的方法:隔离服务进程,为服务提供另一个进程,启动它,启动它不粘,一旦服务破坏就重新创建等等。

唯一有效的是 startForeground() 方法,但我不想使用它,因为它符合设计原则,而且我不想显示有关正在运行的服务的任何通知。

我的问题是下一个:任何人都可以帮助我并告诉我即使应用程序被终止,我如何保持 Socket IO 连接处于活动状态?

这是服务的代码。

package com.github.nkzawa.socketio.androidchat;

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.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "on created", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "start command", Toast.LENGTH_SHORT).show();
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        mSocket.on("newMessageReceived", onNewMessage);
        mSocket.connect();
        return START_STICKY;
    }

    private Emitter.Listener onNewMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            String message = args[0].toString();
            Log.d(TAG, "call: new message ");
            sendGeneralNotification(getApplicationContext(), "1", "new message", message, null);
        }
    };

    private void sendGeneralNotification(Context context, String uniqueId,
                                         String title, String contentText,
                                         @Nullable Class<?> resultClass) {

        NotificationManager notificationManagerCompat = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

        android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
        builder.setAutoCancel(true);


        builder.setContentTitle(title);
        builder.setContentText(contentText);
        builder.setGroup("faskfjasfa");
        builder.setDefaults(android.app.Notification.DEFAULT_ALL);
        builder.setStyle(new NotificationCompat.BigTextStyle()
                .setSummaryText(title)
                .setBigContentTitle(title)
                .bigText(contentText)
        );

        Intent requestsViewIntent = new Intent(context, MainActivity.class);
        requestsViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        requestsViewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent requestsViewPending = PendingIntent.getActivity(context, Integer.valueOf(uniqueId), requestsViewIntent, 0);
        builder.setContentIntent(requestsViewPending);
        builder.setSmallIcon(R.drawable.ic_launcher);

        builder.setShowWhen(true);
        android.app.Notification notification = builder.build();
        notificationManagerCompat.notify(Integer.valueOf(uniqueId), notification);
    }

    private Notification getNotification() {
        Notification notification;
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setColor(getResources()
                .getColor(R.color.material_deep_teal_500))
                .setAutoCancel(true);

        notification = builder.build();
        notification.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_AUTO_CANCEL;

        return notification;
    }
}

不,我既不想使用 firebase 也不想使用任何 3rd 方制造的,因为我现在正在使用一个,而且我会遇到延迟、未收到通知等问题,我会让自己的小方法变得更好.感谢大家的时间和耐心。

【问题讨论】:

  • 嗯,我想我问了非常可怕的问题吧?没有人更接近试图回答或给出一个最小的暗示
  • 嗨,Volo,我也面临完全相同的问题,您是否找到任何方法来实现它,如果可以,您可以将其分享为您自己的答案,提前谢谢您。
  • 在这里找到完整的服务器和客户端解决方案stackoverflow.com/a/45099689/5063805

标签: android sockets service threadpool background-task


【解决方案1】:

在后台实现 Socket.io 并不是最好的主意。 Socket.io 对您的服务器有一个有效的 ping。短时间使用是可以的,但在后台就不行了。

解决问题的最佳方法是结合 Socket.io 和 FCM/GCM 主题来发出广播。在用户设备上,检测是否有活动的 Socket.io 连接,如果退出则忽略 FCM,否则执行 FCM。

【讨论】:

  • 怎么样?可以在 github 中有示例或 repo。我知道使用 fcm 可以在后台和终止模式下接收通知,但是把这段代码放在哪里,因为我看到了在服务中使用 socket.io 的其他示例 其他示例创建了扩展 Application 的其他类
【解决方案2】:

在服务中试试这个:

@Override
public void onCreate() {
    super.onCreate();
    PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
    mWakeLock.acquire();
}

不要忘记许可:

<uses-permission android:name="android.permission.WAKE_LOCK" />

【讨论】:

  • 在服务中试试这个,不要忘记权限:
  • 请使用edit链接将解释添加到您的答案中
【解决方案3】:

在您的服务类中实现此方法并尝试使用此方法。

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);


Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());

    restartServiceIntent.setPackage(getPackageName());
    restartServiceIntent.putExtra("NODE CONNECTED", true);
    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().
            getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);
}

当您终止应用并重新启动后台服务时,将调用此方法。

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 2012-12-16
    • 1970-01-01
    • 2022-09-28
    • 2017-03-07
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    相关资源
    最近更新 更多