我想在Android应用程序中进行后台服务,即使应用程序关闭也应继续运行

时间:2018-06-12 20:11:29

标签: android background-service

我想在Android应用程序中进行后台服务,即使应用程序处于关闭,被杀死或后台状态时也应始终保持运行,我目前有后台服务,当应用程序最小化但是当我关闭应用程序时杀死了应用程序这是行不通的。如果app杀死,套接字将关闭 即使我用android隔离过程真实.....
我想在任何条件下都可以使用套接字

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){
            }
        }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

根据您想要做的事情,我会看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)
} 

答案 1 :(得分:0)

您可以使用Android框架API中的JobScheduler来安排任务或在后台工作。您还可以指定网络类型或要运行作业的时间段或其他一些参数。 创建一个扩展JobService类的类,并覆盖onStartJob和onStopJob方法。

public class myJob extends JobService {
      public boolean onStartJob(JobParameters jobParameters) {
      }
       public boolean onStopJob(JobParameters jobParameters) {
      }
 }

OnStartJob内编写您想要在后台运行的代码。 将其添加到JobInfo,用于配置作业服务的运行方式。

JobInfo.Builder builder = new JobInfo.Builder(jobID, new ComponentName(context, Myjob.service));

在JobInfo.Builder`上,您可以包含计划标准。例如:

    builder.setPeriodic(10000);
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

创建Jobscheduler的实例并传递上面的JobInfo数据。这将根据您指定的调度参数调用JobService类。

JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(builder.build());

以下是有关jobscheduler的更多信息:https://developer.android.com/topic/performance/scheduling