gpt4 book ai didi

android - 如何在 Android 中将套接字事件作为后台服务处理?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:06:13 26 4
gpt4 key购买 nike

我是 Android 开发的新手,我希望我的应用程序即使在应用程序未通过后台服务处于 Activity 状态时也能够检测到套接字事件(这样我就可以推送通知,例如,如果套接字事件触发了一条新消息,例如Whatsapp 和其他人是如何做到的)。

我实现了后台服务和一个启动该服务的应用程序类,但卡住了在我的后台服务中将套接字事件作为可运行任务放置在何处以及如何放置。

我修改了下面的 socket.io android 聊天项目示例并添加了服务和应用程序类。

ChatApplication.java

package com.github.nkzawa.socketio.androidchat;

import android.app.Application;
import android.content.Intent;
import android.content.res.Configuration;

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

import java.net.URISyntaxException;

public class ChatApplication extends Application {

@Override
// called when the application is starting, before any other application objects have been created
public void onCreate() {
super.onCreate();

// represents our background service
Intent background = new Intent(this, SocketBackgroundService.class);
startService(background);
}

private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}

public Socket getSocket() {
return mSocket;
}
}

SocketBackgroundService.java

package com.github.nkzawa.socketio.androidchat;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class SocketBackgroundService extends Service {
private boolean isRunning;
private Thread backgroundThread;

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

@Override
public void onCreate() {
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}

private Runnable myTask = new Runnable() {
@Override
public void run() {
// do something in here
Log.i("INFO", "SOCKET BACKGROUND SERVICE IS RUNNING");

//TODO - how to handle socket events here?
//How do I do something like mSocket.on(Socket.EVENT_CONNECT,onConnect); here?
}
};

@Override
public void onDestroy() {
this.isRunning = false;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if( !this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}

return START_STICKY;
}
}

最佳答案

如果您需要套接字即使在您的应用程序停止后仍处于 Activity 状态。将您的套接字移动到后台服务,然后您可以在该服务中添加套接字事件。

关于android - 如何在 Android 中将套接字事件作为后台服务处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com