服務的最佳實踐--完整版的下載示例

這裏主要是《Android第一行代碼》第二版書中10.6碰到的問題和解決方法,記錄下來但願能幫到你們,也但願你們有更好的解決方案能一塊兒交流.。html

Android Studio版本以下:前端

 

 

這裏我先列出按照書上代碼運行會出現的錯誤:java

(1)、java.net.UnknownServiceException: CLEARTEXT communication to raw.githubusercontent.com not permitted by network security policyandroid

(2)、java.lang.SecurityException: Permission Denial: startForeground from pid=9733, uid=10085 requires android.permission.FOREGROUND_SERVICEgit

(3)、java.io.IOException: unexpected end of stream on http://raw.githubusercontent.com/...github

固然還有一個缺乏Channel的錯誤,那個錯誤比較簡單,在後面的代碼中會有修改的方法,這裏就不贅述了。安全

 

如今主要來看看上面三個錯誤網絡

(1)、第一個錯誤主要是使用Http進行網絡訪問的錯誤,這個有三種解決方法,有興趣的能夠翻看我寫的前面一篇博客,這裏我只給出解決方法,在AndroidManifest.xml中添加以下:閉包

 

<application

    ......

    android:usesCleartextTraffic="true"

    ......

</application>

 

 

 

 


(2)、這個主要Android 9.0版本出現的問題,使用前臺服務時須要申請權限,在AndroidManifest.xml中添加以下:app

 

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

 

 

 

 

 

(3)、這個問題就很隱蔽了,我查找了不少資料才找到的解決方案,在app/build.gradle的android閉包中添加以下:

 

compileOptions{
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8

        }

 

 

 

      這段代碼是爲了開啓Java1.8,可以使用Lambda,說實話我也不明白其中深層的緣由,之後找到的話再回來更新,也但願有大牛能指點其中的原理。

 

沒添加這段代碼程序能夠正常安裝,可是啓動下載的時候就會出現問題,這裏我放兩張圖片

 

 

 

 

 

 

下面咱們來結合書中的代碼完整寫一下這個項目 

一、添加依賴包

編輯app/build.gradle文件,在dependencies閉包中添加以下:

 

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'com.squareup.okhttp3:okhttp:3.14.2'
}

 這裏添加紅色字體就行。

這裏要注意compile已經所有被implementation替代了,因爲以前的項目統一用compile依賴,致使的狀況就是模塊耦合性過高,不利於項目拆解,使用implementation以後雖然使用起來複雜了可是作到下降偶合興提升安全性不失爲一個好辦法。

 

二、定義回調接口

定義一個回調接口,用於對下載過程當中的各類狀態進行監聽和回調,代碼以下:

 

//定義一個回調接口,用於對下載過程當中的各類狀態進行監聽和回調
public interface DownloadListener {
    void onProgress(int progress);        //用於通知當前下載進度

    void onSuccess();                     //用於通知下載成功事件

    void onFailed();                      //用於通知下載失敗事件

    void onPaused();                      //用於通知下載成功事件

    void onCanceled();                    //用於通知下載取消事件
}

 

 

三、編寫下載任務

使用AsyncTask來進行實現。代碼以下:

import android.os.AsyncTask;
import android.os.Environment;

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;




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

    public static final int TYPE_SUCCESS=0;
    public static final int TYPE_FAILED=1;
    public static final int TYPE_PAUSED=2;
    public static final int TYPE_CANCELED=3;

    private DownloadListener listener;

    private boolean isCanceled=false;

    private boolean isPaused=false;

    private int lastProgress;

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

    @Override
    protected Integer doInBackground(String... params) {
        InputStream is=null;
        RandomAccessFile savedFile=null;
        File file=null;
        try{
            long downloadedLength=0;                                   //記錄已下載的文件長度
            String downloadURL=params[0];
            String fileName=downloadURL.substring(downloadURL.lastIndexOf("/"));
            String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file=new File(directory+fileName);
            if(file.exists()){
                downloadedLength=file.length();
            }
            long contentLength=getContentLength(downloadURL);
            if(contentLength==0){
                return TYPE_FAILED;
            }else if(contentLength==downloadedLength){
                //已下載字節和文件總字節相等,證實下載完成
                return TYPE_SUCCESS;
            }
            OkHttpClient client=new OkHttpClient();
            Request request=new Request.Builder()                                        //斷點下載,制定從哪一個字節開始下載
                    .addHeader("RANGE","bytes="+downloadedLength+"-")
                    .url(downloadURL)
                    .build();
            Response response=client.newCall(request).execute();
            if(request!=null){
                is=response.body().byteStream();
                savedFile=new RandomAccessFile(file,"rw");
                savedFile.seek(downloadedLength);                       //跳過已下載的字節
                byte[] b=new byte[1024];
                int total=0;
                int len;
                while((len=is.read(b))!=-1){
                    if(isCanceled){
                        return TYPE_CANCELED;
                    }else if(isPaused){
                        return TYPE_PAUSED;
                    }else{
                        total+=len;
                        savedFile.write(b,0,len);

                        //計算下載的百分比
                        int progress=(int)((total+downloadedLength)*100/contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(is!=null){
                    is.close();
                }
                if(savedFile!=null){
                    savedFile.close();
                }
                if(isCanceled&&file!=null){
                    file.delete();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

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

    @Override
    protected void onPostExecute(Integer status){
        switch(status){
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;

            case TYPE_FAILED:
                listener.onFailed();
                break;

            case TYPE_PAUSED:
                listener.onPaused();
                break;

            case TYPE_CANCELED:
                listener.onCanceled();
                break;

                default:
                    break;

        }
    }

    public void pauseDownload(){
        isPaused=true;
    }

    public void cancelDownload(){
        isCanceled=true;
    }


    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;
    }
}

 

這部分按照書中的代碼便可。

 

 

四、建立下載服務

爲了保證DownloadTask能夠一直在後臺運行,建立下載服務,代碼以下:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

import java.io.File;

import androidx.core.app.NotificationCompat;

//爲了保證DownloadTask能夠一直在後臺運行
public class DownloadService extends Service {

    private DownloadTask downloadTask;
    private String downloadUrl;

    private DownloadListener listener=new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            //構建顯示下載進度的通知,並觸發通知
            getNotificationManager().notify(1, getNotification("Downloading ...",progress));
        }

        @Override
        public void onSuccess() {
            downloadTask=null;
            //下載成功將前臺服務關閉,並建立一個下載成功的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Success",-1));
            Toast.makeText(DownloadService.this,"Download Success",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFailed() {
            downloadTask=null;
            //下載失敗將前臺服務關閉,並建立一個下載失敗的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Failed",-1));
            Toast.makeText(DownloadService.this,"Download Failed",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPaused() {
            downloadTask=null;

            Toast.makeText(DownloadService.this,"Download Pause",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCanceled() {
            downloadTask=null;
            stopForeground(true);
            Toast.makeText(DownloadService.this,"Download Canceled",Toast.LENGTH_SHORT).show();

        }
    };

    private DownloadBinder mBinder=new DownloadBinder();

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

    class DownloadBinder extends Binder {
        public void startDownload(String url){
            if(downloadTask==null){
                downloadUrl=url;
                downloadTask=new DownloadTask(listener);
                downloadTask.execute(downloadUrl);
                startForeground(1,getNotification("Downloading...",0));
                Toast.makeText(DownloadService.this,"Downloading...",Toast.LENGTH_SHORT).show();
            }
        }

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

        public void cancelDownload(){
            if(downloadTask!=null){
                downloadTask.cancelDownload();
            }
            if(downloadUrl!=null){
                //取消下載時需將已下載文件刪除,並將通知關閉
                String filename=downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                File file=new File(directory+filename);
                if(file.exists()){
                    file.delete();
                }
                getNotificationManager().cancel(1);
                stopForeground(true);
                Toast.makeText(DownloadService.this,"Canceled",Toast.LENGTH_SHORT).show();
            }
        }
    }

    //獲取NotificationManager實例
    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);

        NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel=null;
        Uri uri= Settings.System.DEFAULT_NOTIFICATION_URI;

        //Android8.0以後的版本要求設置通知渠道
        if(android.os.Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            channel=new NotificationChannel("Notification","This is 2",NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("This is 1");
            channel.setSound(uri,Notification.AUDIO_ATTRIBUTES_DEFAULT);
            manager.createNotificationChannel(channel);

        }


        NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher));
        builder.setWhen(System.currentTimeMillis());
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        builder.setChannelId("Notification");
        builder.setAutoCancel(true);
        if(progress>=0){
            //當progress大於或等於0時才顯示下載進度
            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
        }
        return builder.build(); }
}

 

這裏將須要修改的代碼用紅色標出了,這部分和書上的代碼有區別主要緣由是在Android 8(API 26)以後引入了Channel,全部的Notification都要指定Channel(通道),對於每個Channel你均可以單獨去設置它;好比通知開關、提示音、是否震動或者是重要程度等;這樣每一個應用程序的通知在用戶面前都是透明的。

 

這裏就不詳細講了,這裏我找了一個總結的比較精簡的,有興趣的能夠參考:https://www.jianshu.com/p/b529e61d220a

 

 

五、編寫前端代碼

修改activity_main.xml中的代碼,以下所示:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/start_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Start Download"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/pause_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pause download"
            android:textAllCaps="false" />

        <Button
            android:id="@+id/cancel_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Cancel download"
            android:textAllCaps="false" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

 

這裏我爲了省功夫直接將LinearLayout嵌套在Constranintlayout裏使用了,對界面沒有影響,和書中代碼是同樣的,最後咱們來修改MainActivity中的代碼,代碼以下:

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "MainActivity";
    private DownloadService.DownloadBinder downloadBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder=(DownloadService.DownloadBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startDownload=(Button)findViewById(R.id.start_download);
        Button pauseDownload=(Button)findViewById(R.id.pause_download);
        Button cancelDownload=(Button)findViewById(R.id.cancel_download);
        startDownload.setOnClickListener(this);
        pauseDownload.setOnClickListener(this);
        cancelDownload.setOnClickListener(this);

        //啓動服務
        Intent intent=new Intent(this,DownloadService.class);
        startService(intent);

        //綁定服務
        bindService(intent,connection,BIND_AUTO_CREATE);

        //判斷是否有訪問內存的權限
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.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://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
                Log.d(TAG, "onClick: ");
                downloadBinder.startDownload(url);
                break;
            case R.id.pause_download:
                downloadBinder.pauseDownload();
                break;
            case R.id.cancel_download:
                downloadBinder.cancelDownload();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]!=PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"拒絕權限將沒法使用程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

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

 

 

 

 

 

六、配置文件

 

添加以下代碼:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

 

 

這裏主要是申請網絡訪問、訪問SD卡和使用前臺服務的權限。

在application標籤中添加代碼以下:

<application

    ......

    android:usesCleartextTraffic="true"

    ......

</application>

 

在app/build.gradle的android閉包中添加以下:

compileOptions{
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }

 

 

至此,這個下載項目就能正常運行了。

 剛接觸Android不久,有錯誤還請你們指正,但願能和你們多交流。

相關文章
相關標籤/搜索