第九章(探究服务Service、Binder、线程、Messag

2018-07-11  本文已影响84人  Yolyn

探究服务(Service、IntentService、Handler、AsyncTask)

首先需要知道的几个知识点:

  1. 什么是服务(Service):Service是Android中实现程序后台运行的解决方案,它非常适合去执行那些不需要和用户交互而且还要求长期运行的任务。服务的运行不依赖于任何用户界面,及时程序被切换到后台,或者用户打开了另一个应用程序,服务仍然能保持正常运行。
  2. 服务不是运行在一个单独的进程中,而是依赖于创建服务时所在的应用程序进程,当某个应用程序进程被杀掉时,则依赖于该进程的服务也会停止运行
  3. 不要被服务的后台概念所迷惑,实际上服务不会自动去开启线程,所有的代码都是默认运行在主线程当中的,也就是说我们需要在服务的内部手动创建子线程,并在这里执行具体的任务,否则容易造成主线程阻塞

4. 线程的基本使用方法

public class MyThread extends Thread {
    @Override
    public void run() {
      //这里处理相应的逻辑
    }
}

然后只需要new出一个MyThread的实例调用它的start方法(new MyThread.start()),这样run方法的代码就能在子线程中运行了。

public class MyThread implements Runnable {

    @Override
    public void run() {
        
    }
}

然后可以这样开启一个子线程,Thread的构造函数接收一个Runnable参数,再调用start方法,

MyThread myThread=new MyThread();
new Thread(myThread).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //在这里处理相应的逻辑
            }
        }).start();
  1. 在子线程中更新UI
    Android的UI也是线程不安全的,也就是说要更新程序里的UI元素,必须在主线程中进行,否则就会出异常。

6. Handler

如果在子线程中直接更新UI的话就会报错,那么怎么解决呢,Android提供了很好的一套很好的异步消息处理机制,有些时候我们需要在子线程中进行耗时操作,然后根据结果来更新UI控件,就可以使用这样的机制,例如Handler,下面举个例子

public class UITest1 extends AppCompatActivity implements View.OnClickListener {
    private TextView textView;
    private Button changetextviewByHandler;
    public static final int UPDATATEXTVIEW = 1;
    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //重写父类的handleMessage方法
            switch (msg.what) {
                case UPDATATEXTVIEW:
                    textView.setText(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uitest1);
        textView = findViewById(R.id.textView);
        changetextviewByHandler=findViewById(R.id.change_textview_byHandler);
        changetextviewByHandler.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.change_textview_byHandler:
                Message message = new Message();
                message.what = UPDATATEXTVIEW;
                message.obj = "Nice To Meet You Too";
                myHandler.sendMessage(message);
                break;
            default:
                break;
        }
    }

我们来介绍一下这个异步消息处理机制:
Android中的异步消息处理主要由四个部分组成:Message、Handler、MessageQueue和Looper

  1. AsyncTask
    借助AsyncTask,即使对异步消息处理机制完全不了解,也可以十分简单地从子线程切换到主线程,当然AsyncTask背后实现的原理也是基于异步消息处理机制,只是Android做好了封装。
    AsyncTask是一个抽象类,如果要使用它,就得创建一个类继承它并指定三个泛型参数。用途如下:

再重写它的方法

7.服务

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //Service中的唯一抽象方法
        return mBinder;
    }

上面这个方法是Service里面唯一的抽象方法,所以在创建服务的时候必须要重写这个方法,暂时忽略掉,后面再讲这个方法。

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />
public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //Service中的唯一抽象方法
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();//每次服务创建的时候调用
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy:");
    }
}

(2). 在布局创建两个Button用来启动和停止服务

     <?xml version="1.0" encoding="utf-8"?>
     <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
     tools:context=".MainActivity">
     <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="启动服务"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.051" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="停止"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/start"
        app:layout_constraintVertical_bias="0.024" />
      </android.support.constraint.ConstraintLayout>

(3). 修改MainActivity

package com.example.houchongmu.servicetest;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "MainActivity";
    private Button start;
    private Button stop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = findViewById(R.id.start);
        stop = findViewById(R.id.stop);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                Intent start = new Intent(this, MyService.class);
                startService(start);
                break;
            case R.id.stop:
                Intent stop = new Intent(this, MyService.class);
                stopService(stop);
                break;
            default:
                break;
        }
    }
}

在点击事件里面先构建出一个Intent对象,然后调用startService和stopService来启动服务和关闭服务。注意的是这两个方法都是在Context类中定义的,所以在Activity中就可以直接调用这个方法,这里完全是由活动来决定服务合适关闭的,如果没有点击stopService那么服务就会一直运行,但是可以在Service的任意位置调用stopSelf让服务停止。
我们点击start按钮后就可以在手机设置的Running services里面看到这个服务了。

(1)在Service里面新建一个DownloadBind继承Binder并创建startDownload和stopDownload方法,然后在onBind方法中将我们创建的mBinder对象返回出去。

public class MyService extends Service {
    private DownloadBinder mBinder = new DownloadBinder();

    class DownloadBinder extends Binder {
        //想要服务干什么,只要在服务内部定义一个类继承Binder,在这个了内部完成动作即可
        //然后在onBind方法里面将这个类返回出去
        //Binder是IBinder的实现类
        public void startDownload() {
            Log.d(TAG, "startDownload executed");
        }

        public int getProgress() {
            Log.d(TAG, "getProgress executed");
            return 0;
        }

    }

    public static final String TAG = "MyService";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //Service中的唯一抽象方法
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();//每次服务创建的时候调用
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                //在这里处理相应的逻辑
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
        //每次服务启动的时候调用
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy:");
    }
}

(2)在布局中新增两个按钮

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="启动服务"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.051" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="停止"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/start"
        app:layout_constraintVertical_bias="0.024" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/stop"
        app:layout_constraintVertical_bias="0.316" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="取现绑定"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/stop"
        app:layout_constraintVertical_bias="0.26" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="绑定服务"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/stop"
        app:layout_constraintVertical_bias="0.033" />

</android.support.constraint.ConstraintLayout>

这两个按钮用于绑定服务和取消绑定服务
(3)在绑定服务之前我们首先要在MainActivity中创建之前在服务里面定义的DownloaderBinder对象,然后创建一个ServiceConnection的匿名类,在这个匿名类里面重写onServiceConnected和onServiceDisconnected方法,这两个方法是在服务于活动进行绑定和取消绑定的时候调用的。看具体代码。

   private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;//接收MyService里面onBind方法里面返回的Binder
            downloadBinder.startDownload();
            downloadBinder.getProgress();
            //活动与服务绑定的时候调用
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //活动与服务解绑的时候调用
        }
    };

onServiceConnected方法里面IBinder是接收Service中onBind方法返回的Binder,然后在onServiceConnected里面调用MyService.DownloadBinder的public方法,这样一来我们的服务就和Activity变得联系紧密了。

  public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                Intent start = new Intent(this, MyService.class);
                startService(start);
                break;
            case R.id.stop:
                Intent stop = new Intent(this, MyService.class);
                stopService(stop);
                break;
            case R.id.bind_service:
                Intent bindIntent = new Intent(this, MyService.class);
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                //会回调Service里面的onBind方法
                //第三个参数表示活动和服务绑定后自动创建服务
                break;
            case R.id.unbind_service:
                unbindService(connection);//解绑服务
                //用bindService启动的服务必须用unbindService才能停止
                break;
            default:
                break;
        }

    }

8.前台服务

服务几乎都是在后台运行的,而且服务的系统优先级是比较低的,当系统出现内存不足时,就有可能回收掉正在后台运行的服务,如果希望服务不被系统回收掉就可以考虑使用前台服务,前台服务和后台服务的最大区别是前台服务有一个正在运行的图标在系统状态栏显示。类似通知的效果,所以就得在Service里面定义一个Notification。

    @Override
    public void onCreate() {
        super.onCreate();//每次服务创建的时候调用
        Log.d(TAG, "onCreate: ");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "service";
            String channelName = "服务";
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
        }
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this, "service")
                .setContentTitle("this is content title")
                .setContentText("this is content text")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pi)
                .build();
        startForeground(1, notification);
    }

定义一个Notification然后调用startForeground()方法,传入两个参数,第一个就是Notification的id,第二个就是我们定义的Notification,调用startForeground方法后就会让这个service变成一个前台服务。


image

IntentService

服务中的代码都是默认运行在主线程当中的,如果直接在服务里处理一些耗时的逻辑,就会很容易出现ANR(Application Not Responding),所以这就需要使用多线程技术了,我们可以在服务里面开启一个线程,然后在这个子线程里面去处理相应的逻辑,如果想让这个服务执行结束后自动关闭,就在相应的逻辑后面加上stopSelf方法就行了。

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                //在这里处理相应的逻辑
                stopSelf();
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
        //每次服务启动的时候调用
    }

但是万一忘记调用stopSelf怎么办呢,为了可以更简单地创建一个异步的会自动停止的服务,Android专门提供了一个IntentService类,我们看下面的例子,创建一个MyIntentService类继承IntentService类

package com.example.houchongmu.servicetest;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyIntentService extends IntentService {

    public static final String TAG = "MyIntentService";
    /**
     * 父类的构造函数:
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     *  name: Used to name the worker thread, important only for debugging.
     */
    public MyIntentService() {
        super("MyIntentService");//命名线程名
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(TAG, "onHandleIntent" +"线程id是"+ Thread.currentThread().getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy executed ");
    }
}

里面首先提供了一个无参构造函数,并且必须在其内部调用父类的有参构造函数,并传递一个线程名。然后要在子类中去实现onHandleIntent这个抽象方法,在这个方法中可以处理一些自定义逻辑,这个方法里面的代码是在子线程中运行的。另外这个IntentService中的逻辑执行完之后就会自动停止并调用onDestroy方法。下面看这个服务的启动方法


    public void start_intent_service(View view) {
        Log.d(TAG, "start_intent_service: "+"主线程id是"+Thread.currentThread().getId());
        Intent intentService=new Intent(this,MyIntentService.class);
        startService(intentService);
    }

最后还要在清单文件中进行注册

 <service android:name=".MyIntentService"/>

关于服务就讲到这里,下面看一个比较综合的下载例子。

Service的最佳实践(下载的例子)

我们先简单介绍一下具体的流程。
(1)我们创建一个AsyncTask来实现异步下载。
(2)将这个异步下载的任务放到一个服务里面,以保证第一步定义的任务可以一直在后台运行。
(3)最后使用Binder将这个服务与活动绑定在一起,并在这个Binder里面提供开始下载、暂停和取消的功能。
下面看具体步骤:
1.添加okhttp的依赖库

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

2.定义一个回调接口,对下载的各种状态进行监听

package com.example.houchongmu.myservicebestpractice1;

public interface DownloadListener {
    void onProgress(int progress);//通知当前的下载进度

    void onSuccess();//通知下载成功事件

    void onFailed();//通知下载失败事件

    void onPaused();//通知下载暂停事件

    void onCanceled();//通知下载取消事件
//    这里提供了五个回调方法
}

2.创建一个DownloadTask继承AsyncTask

package com.example.houchongmu.myservicebestpractice1;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.os.Environment.DIRECTORY_DOWNLOADS;

public class DownloadTask extends AsyncTask<String, Integer, Integer> {
    public static final int FAILED = 0;
    public static final int CANCELED = 1;
    public static final int PAUSED = 2;
    public static final int SUCCESSED = 3;
    private boolean isCanceled = false;
    private boolean isPaused = false;
    private int lastProgress;
    private DownloadListener listener;
    private File file = null;

    public DownloadTask(DownloadListener listener) {
        this.listener = listener;

    }

    @Override
    protected Integer doInBackground(String... params) {
        InputStream is = null;
        RandomAccessFile savaFile = null;

        try {
            long downloadedLength = 0;
            String downloadUrl = params[0];
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS).getPath();//SD卡的Download目录
            file = new File(directory + fileName);
            if (file.exists()) {
                downloadedLength = file.length();
            }
            long contentLength = getContentLength(downloadUrl);
            if (contentLength == 0) {
                return FAILED;//调用onPostExecute方法
            } else if (contentLength == downloadedLength) {
                return SUCCESSED;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(downloadUrl)
                    .addHeader("Range", "bytes=" + downloadedLength + "-")
                    .url(downloadUrl)
                    .build();//下载过的内容不用重复下载以实现断点下载
            Response response = client.newCall(request).execute();
            if (response != null) {
                is = response.body().byteStream();
                savaFile = new RandomAccessFile(file, "rw");
                savaFile.seek(downloadedLength);//跳过已下载的字节
                byte[] bys = new byte[1024];
                int total = 0;
                int len;
                while ((len = is.read(bys)) != -1) {
                    if (isCanceled) {
                        return CANCELED;
                    } else if (isPaused) {
                        return PAUSED;
                    } else {
                        total += len;
                        savaFile.write(bys, 0, len);
                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);
                        publishProgress(progress);//更新进度,调用onProgressUpdate方法
                    }
                }
                response.body().close();
                return SUCCESSED;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (savaFile != null) {
                    savaFile.close();
                }
                if (isCanceled) {
                    if (file.exists()) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return FAILED;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }

    }

    @Override
    protected void onPostExecute(Integer integer) {
        switch (integer) {
            case FAILED:
                listener.onFailed();
                break;
            case CANCELED:
                listener.onCanceled();
            case PAUSED:
                listener.onPaused();
                break;
            case SUCCESSED:
                listener.onSuccess();
        }
    }

    private long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(downloadUrl).build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();//获取网络文件的长度
            response.body().close();
            return contentLength;
        }
        return 0;
    }

    public void pauseDownload() {
        isPaused = true;
    }

    public void cancelDownload() {
        isCanceled = true;
    }

}

我们来介绍一下这个类。首先AsyncTask中的三个泛型参数:第一个是String,表示doInBackground里面接收的是String类型的参数;第二个参数是Integer,表示使用整型数据来作为进度显示单位,即onProgressUpdate里面接收的类型是Integer;第三个泛型参数是Integer,表示使用整型数据来反馈执行结果,即onPostExecute接收的参数是Integer。定义一个构造函数将DownloadListener的实现类传进去,最后在这个类里面创建了暂停和取消下载的方法pauseDownload和cancelDownload

3.创建一个DownloadService,保证DownloadTask一直在后台执行

package com.example.houchongmu.myservicebestpractice1;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class DownloadService extends Service {
    private DownloadTask downloadTask = null;
    private String downloadUrl;
    private DownloadBinder downloadBinder = new DownloadBinder();
    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            //用于更新下载任务的进度
            NotificationManager manager = getNotificationManager();
            manager.notify(1, getNotification("Downloading", progress));
        }

        @Override
        public void onSuccess() {
            downloadTask = null;
            stopForeground(true);
            getNotification("Download Success", -1);
            Toast.makeText(DownloadService.this, "下载完成", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            downloadTask = null;
            stopForeground(true);
            getNotificationManager().notify(1, getNotification("Download Failed", -1));
            Toast.makeText(DownloadService.this, "下载失败", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPaused() {
            downloadTask = null;
            Toast.makeText(DownloadService.this, "下载暂停", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCanceled() {
            downloadTask = null;
            stopForeground(true);
        }
    };

    class DownloadBinder extends Binder {
        public void startDownload(String url) {
            if (downloadTask == null) {
                downloadTask = new DownloadTask(listener);
                downloadTask.execute(url);
                startForeground(1, getNotification("Downloading...", 0));//这样会在系统状态栏创建一个持续运行的通知
                Toast.makeText(DownloadService.this, "正在下载", Toast.LENGTH_SHORT).show();
            }
        }

        public void pauseDownload() {
            if (downloadTask != null) {
                downloadTask.pauseDownload();
            }
        }

        public void cancelDownload() {
            if (downloadTask != null) {
                downloadTask.cancelDownload();
            }
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("xiazai", "下载服务", NotificationManager.IMPORTANCE_DEFAULT);
            getNotificationManager().createNotificationChannel(channel);
        }
    }

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

    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title, int progress) {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "xiazai")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pi)
                .setContentTitle(title);
        if (progress >= 0) {
        //当progress大于或等于0的时候才显示进度条
            builder.setContentText(progress + "%")
                    .setProgress(100, progress, false);
        }
        return builder.build();
    }

}

在这个类里面我们首先创建了DownloadListener的匿名实现类,并实现了之前定义的五个方法,这五个方法就是使下载状态在通知里面显示。为了让DownloadService能和活动通信,又创建了一个DownloadBinder,在里面提供了startDownload、pauseDownload和cancelDownload方法,在onBind方法里面将这个DownloadBinder的实例返回。

4.MainActivity

package com.example.houchongmu.myservicebestpractice1;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private DownloadService.DownloadBinder downloadBinder;//=new DownloadService().new DownloadBinder()
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private Button startDownload;
    private Button pauseDownload;
    private Button cancelDownload;
    private Button deleteDownloadedFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startDownload = findViewById(R.id.start_download);
        pauseDownload = findViewById(R.id.pause_download);
        cancelDownload = findViewById(R.id.cancel_download);
        deleteDownloadedFile = findViewById(R.id.delete_file);
        startDownload.setOnClickListener(this);
        pauseDownload.setOnClickListener(this);
        cancelDownload.setOnClickListener(this);
        deleteDownloadedFile.setOnClickListener(this);
        Intent service = new Intent(this, DownloadService.class);
        startService(service);
        bindService(service, connection, BIND_AUTO_CREATE);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }


    @Override
    public void onClick(View v) {
        if (downloadBinder == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.start_download:
                String url = "http://10.0.2.2/test.apk";
                downloadBinder.startDownload(url);
                break;
            case R.id.pause_download:
                if (downloadBinder != null) {
                    downloadBinder.pauseDownload();
                }
                break;
            case R.id.cancel_download:
                if (downloadBinder != null) {
                    downloadBinder.cancelDownload();
                }
                break;
            case R.id.delete_file:
                File file =new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/test.apk");
                if(file.exists()){
                    file.delete();
                    Toast.makeText(this,"文件删除成功",Toast.LENGTH_SHORT).show();
                    break;
                }else{
                    Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "您已经同意了写入文件的权限", Toast.LENGTH_SHORT).show();
                } else if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "拒接权限将无法使用", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;


        }
    }
}

综合性有点高,理解起来可能有点费劲,但是拆开来看要好理解很多,先是在AsyncTask中实现下载任务,然后创建一个服务是这个AsyncTask能一直在后台运行,最后利用Binder将这个服务与活动绑定。


image
上一篇下一篇

猜你喜欢

热点阅读