当前位置: 首页 > 知识库问答 >
问题:

我想在android应用程序中做后台服务,即使在应用程序关闭的时候也应该保持运行

暴绪
2023-03-14

我想在android应用程序中做后台服务,即使当应用程序处于关闭、杀死或后台状态时,它也应该始终保持运行,我目前有后台服务,当应用程序最小化时,它工作得很好,但当我关闭应用程序时,杀死应用程序时,它不工作。如果应用程序死亡,套接字是关闭的,即使我使用了android隔离进程true...
我想让套接字在任何情况下都可用

public class MyTestService extends IntentService {

private ServerSocket serverSocket;
private Socket tempClientSocket;
Thread serverThread = null;
public static final int SERVER_PORT = 3001;

public MyTestService() {
    // Used to name the worker thread, important only for debugging.
    super("test-service");
}

@Override
public void onCreate() {
    super.onCreate(); // if you override onCreate(), make sure to call super().
    // If a Context object is needed, call getApplicationContext() here.
}

@Override
protected void onHandleIntent(Intent intent) {
    Socket socket;
    try {
        serverSocket = new ServerSocket(SERVER_PORT);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (null != serverSocket) {
        while (true) {
            try {
                socket = serverSocket.accept();
                try {
                    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String mess = input.readLine();
                    BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    PrintWriter out = new PrintWriter(bf,true);
                    out.println("message recieve");
                    input.close();
                    bf.close();
                    serverSocket.close();

                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "asdsadasd")
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle("Title")
                            .setContentText(mess)
                            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                            .setAutoCancel(true);

                    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
                    notificationManager.notify(1, mBuilder.build());
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
        catch (Exception e){
            }
        }
    }
  }
}

共有1个答案

锺离珂
2023-03-14

具体取决于您想要做什么,我将查看WorkManager。

fun workRequest() {

    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.CONNECTED)
        .setRequiresCharging(true)
        .setRequiresDeviceIdle(true)
        .build()

    val worker: WorkRequest =
        PeriodicWorkRequestBuilder<DetailsWorker>(6, TimeUnit.HOURS)
            .setInputData(workRequestData)
            .setConstraints(constraints)
            .build()

    WorkManager.getInstance().enqueue(worker)
} 
 类似资料: