首页 > 解决方案 > 谁能用 service 和 asyncTask 向我解释我的简单应用程序中的服务?

问题描述

我有一个带有 Service 和 AsyncTask 类的简单应用程序。当我启动服务时,扩展 AsyncTask 的 BackgroundTask 类会运行一些模拟任务并显示一些进度。这里在同一个BackgroundTask类中,我不明白为什么类构造函数中是Service服务,为什么在MyService类的onStartCommand方法BackgroundTask构造函数中接受这个作为参数。

MainActivity 类:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btnStartService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = findViewById(R.id.btnStartService);
        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getApplicationContext(), MyService.class);
                startService(intent);

            }
        });
    }
}

我的服务类:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    private static final int TASK_COUNT = 3;
    private boolean serviceOn = false;

    public MyService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (!serviceOn){
            Toast.makeText(this, "Service starting...", Toast.LENGTH_SHORT).show();
            BackgroundTask backgroundTask = new BackgroundTask(this);
            backgroundTask.execute(TASK_COUNT);
            serviceOn = true;
        }else{
            Toast.makeText(this, "Service has already started...", Toast.LENGTH_SHORT).show();
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service stoped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

背景任务类:

import android.app.Service;
import android.os.AsyncTask;
import android.widget.Toast;

public class BackgroundTask extends AsyncTask<Integer, Integer, String> {


    private Service service;


    public BackgroundTask(Service service) {
        this.service = service;
    }


    @Override
    protected String doInBackground(Integer... integers) {
        int taskCount = integers[0];
        for (int i = 0; i < taskCount;i++){
            performLongTask();
            publishProgress((int) ((i+1) / (float) taskCount * 100));
        }
        String result = taskCount + " "+service.getString(R.string.finished);

        return result;
    }

    private void performLongTask() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        String text = values[0] + "% " + service.getResources().getString(R.string.finished);
        Toast.makeText(service, text, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPostExecute(String s) {
        Toast.makeText(service, s+" mark", Toast.LENGTH_SHORT).show();
        service.stopSelf();
    }
}

问题:

  1. BackgroundTask 类构造函数中“服务服务”的含义是什么,为什么这个类在 MyService 类的 onStartCommand 方法中接受“this”作为参数?
  2. 由于 stopSelf 方法的服务需要,我可以在 BackgroundTask 类中使用“上下文上下文”或与“服务服务”的某种组合来代替“服务服务”吗?
  3. 如何使用以下代码在 BackgroundTask 类中使用服务引用字符串资源:“service.getString(R.string.finished);”?

标签: androidandroid-asynctaskandroid-serviceandroid-context

解决方案


在您的用例中,我认为您不需要从“MyService”开始。只需使用 AsyncTask 即可。特别是“MyService”仍然在 UI 线程上运行,所以我看不到用服务包装 AsyncTask 的意义。

另外,不要将 Context/Service/Activity 传递给 AsyncTask,因为这会形成显式引用并可能导致内存泄漏。


推荐阅读