Download Manager 시스템 자체 다운로드 클래스 Jetpack
                                            
 17502 단어  android
                    
둘, 9.0 http 사이트 에 접근 하면 추가 하 는 것 을 기억 하 세 요.
android:usesCleartextTraffic="true"3. 등록 감청 기 ContentObserver (다운 로드 를 실행 하기 전에 콘 텐 츠 감청 자 를 등록 해 야 함) 세 가지 인 자 는 각각 감청 할 Uri, false 가 이 Uri 와 정확하게 일치 하 는 것 을 나타 내 고 true 는 파생 된 Uri, ContentObserver 의 파생 인 스 턴 스 와 일치 할 수 있 음 을 나타 낸다.
1. 기초 (대충 보면 돼 요. 코드 를 보면 어떻게 쓰 는 지 알 수 있어 요)
2. 방송 수신 자 를 통 해 다운로드 상 태 를 감청
public class DownUtils {
    private DownResultListener downResultListener=null;
    private static final String TAG = "DownUtils";
    //   
    private DownloadManager downloadManager=null;
    //   ID
    private long downloadId=-1;
    private String pathstr="";
    private boolean downingFlag=false;
    /**
     *   apk     ,              
     * @param mContext
     * @param url
     * @param downFileName       ,    ,  :myjst.apk
     * @param showInNotify
     * @param notifyTitle
     * @param notifyMsg
     * @param listener
     * @return
     */
    public boolean downloadTask(Context mContext, String url, String downFileName,
                                boolean showInNotify, String notifyTitle, String notifyMsg, DownResultListener listener) {
        if(downingFlag){
            return false;
        }else{
            downingFlag=true;
        }
        downloadId=-1;
        this.downResultListener=listener;
        //      
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //             
        request.setAllowedOverRoaming(false);
        //         
        if(showInNotify){
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }else{
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        }
        //        
        //
        //request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        //             
        request.setTitle(notifyTitle);
        //             
        request.setDescription(notifyMsg);
        request.setVisibleInDownloadsUi(true);
        //   setAllowedNetworkTypes                ,
        //      setAllowedOverRoaming  ,     
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //     
        //request.setMimeType("application/zip");
        //       
        File file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), downFileName);
        request.setDestinationUri(Uri.fromFile(file));
        pathstr = file.getAbsolutePath();
        //request.setDestinationInExternalPublicDir("DownloadManagerTest", "myjst.apk");
        //  DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //           ,                long  id,   id      ,    、         
        if (downloadManager != null) {
            downloadId = downloadManager.enqueue(request);
        }else{
            downingFlag=false;
            return false;
        }
        //        ,            
        //apk    ,            ,    application   (  )     
        //       ,     app      。
        //    ,
        // 1、 application   (  )     
        // 2、  apk   id=-1        ,   id==-1,       
        //       ,      
        mContext.registerReceiver(receiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        return true;
    }
    //           
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(downloadId==-1){
                return;
            }
            checkStatus(context);
        }
    };
    //      
    private void checkStatus(Context context) {
        DownloadManager.Query query = new DownloadManager.Query();
        //     id  
        query.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //    
                case DownloadManager.STATUS_PAUSED:
                    Log.e(TAG, "queryUri: STATUS_PAUSED");
                    break;
                //    
                case DownloadManager.STATUS_PENDING:
                    Log.e(TAG, "queryUri: STATUS_PENDING");
                    break;
                //    
                case DownloadManager.STATUS_RUNNING:
                    Log.e(TAG, "queryUri: STATUS_RUNNING");
                    break;
                //    
                case DownloadManager.STATUS_SUCCESSFUL:
                    Log.e(TAG, "queryUri: STATUS_SUCCESSFUL");
                    if(downResultListener!=null){
                        downResultListener.onSuccess(context,pathstr);
                        downResultListener=null;
                    }
                    downloadId=-1;
                    context.unregisterReceiver(receiver);
                    downingFlag=false;
                    break;
                //    
                case DownloadManager.STATUS_FAILED:
                    Log.e(TAG, "queryUri: STATUS_FAILED");
                    if(downResultListener!=null){
                        downResultListener.onFail(context,"  ");
                        downResultListener=null;
                    }
                    downloadId=-1;
                    context.unregisterReceiver(receiver);
                    downingFlag=false;
                    break;
            }
        }
        cursor.close();
    }
    public interface DownResultListener{
        public void onSuccess(Context context,String filePath);
        public void onFail(Context context,String msg);
    }
}
 호출 방법:
 new DownUtils().downloadTask(this, PATH, "myjst.apk", true
                ,"title","msg des` ", new DownUtils.DownResultListener() {
                    @Override
                    public void onSuccess(Context context, String filePath) {
                        Tools.installAPK(context,new File(filePath));
                        Toast.makeText(context, "    ", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onFail(Context context, String msg) {
                        Toast.makeText(context, "    ", Toast.LENGTH_SHORT).show();
                    }
                });3. 실시 간 으로 다운로드 진 도 를 가 져 옵 니 다.(이 demo 는 연습 일 뿐 거 칠 게 썼 으 니 실전 때 스스로 수정 해 야 합 니 다)
public class DownLoadActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final String PATH = "http://xxx/rch.apk";
    private long mId = -1;
    private DownloadManager mDownloadManager;
    private DownloadManager.Query mQuery;
    private Uri mUri;
    private Handler myHandler=new Handler();
    private DownloadStatusObserver observer = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down_load);
        //   DownloadManager  
        mDownloadManager = (DownloadManager) this.getSystemService(DOWNLOAD_SERVICE);
        observer = new DownloadStatusObserver(myHandler);
        //             
        registerContentObserver();
    }
    /**
     *     
     */
    public void downLoad(View view) {
        doSuccess=false;
        /*   onCreate
        //   DownloadManager  
        mDownloadManager = (DownloadManager) this.getSystemService(DOWNLOAD_SERVICE);
        observer = new DownloadStatusObserver(myHandler);
        //             
        registerContentObserver();*/
        //         
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(PATH));
        //                
        // setDestinationUri
        // setDestinationInExternalPublicDir
        request.setDestinationInExternalPublicDir("DownloadManagerTest", "myjst.apk");
        //             
        request.setTitle("python");
        //             
        request.setDescription("python desc");
        //         
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //   setAllowedNetworkTypes                ,
        //      setAllowedOverRoaming  ,     
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setVisibleInDownloadsUi(true);
        //     
        request.setMimeType("application/zip");
        //     ,  downloadId,downloadId           。        、Sdcard   、               ,       。
        mId = mDownloadManager.enqueue(request);
        //             
        Long maxBytesOverMobile = DownloadManager.getMaxBytesOverMobile(this);
        Log.e(TAG, "downLoad: maxBytesOverMobile ---------" + maxBytesOverMobile);
        //               
        Long recommendedMaxBytesOverMobile = DownloadManager.getRecommendedMaxBytesOverMobile(this);
        Log.e(TAG, "downLoad: recommendedMaxBytesOverMobile ---------" + recommendedMaxBytesOverMobile);
    }
    /**
     *   ContentObserver
     */
    private void registerContentObserver() {
        /** observer download change **/
        if (observer != null) {
            //            Uri、false       Uri,true          Uri、ContentObserver      
            getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, observer);
        }
    }
    /**
     *       
     */
    public void unDownLoad(View view) {
        //     ,        。            。
        mDownloadManager.remove(mId);
    }
    /**
     *       
     */
    public void queryUri(View view) {
        queryDownFileInfo();
    }
    private void queryDownFileInfo() {
        //   Uri     
        mUri = mDownloadManager.getUriForDownloadedFile(mId);
       /* if(mUri!=null){
            getContentResolver().unregisterContentObserver(observer);
            getContentResolver().registerContentObserver(mUri, true, observer);
        }*/
        Log.e(TAG, "queryUri: uri--------" + mUri);
        //         
        mQuery = new DownloadManager.Query().setFilterById(mId);
        //               
        Cursor cursor = mDownloadManager.query(mQuery);
        if (null != cursor) {
            if (cursor.moveToFirst()) {
                //       
                String fileUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
                Log.e(TAG, "queryUri: fileUri ---------" + fileUri);
                //       
                int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                Log.e(TAG, "queryUri: " + status);
                logStatus(status);
            }
            cursor.close();
        }
    }
    /**
     *       
     *
     * @param downloadId   ID
     * @return
     */
    public int[] getBytesAndStatus(long downloadId) {
        int[] bytesAndStatus = new int[]{-1, -1, 0};
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = null;
        try {
            c = mDownloadManager.query(query);
            if (c != null && c.moveToFirst()) {
                //         
                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //       
                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //       
                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return bytesAndStatus;
    }
    class DownloadStatusObserver extends ContentObserver {
        DownloadStatusObserver(Handler handler) {
            super(handler);
        }
        @Override
        public void onChange(boolean selfChange) {
            try {
                if(mId!=-1){
                    int[] bytesAndStatus = getBytesAndStatus(mId);
                    //    
                    int currentSize = bytesAndStatus[0];
                    //   
                    int totalSize = bytesAndStatus[1];
                    //    
                    int status = bytesAndStatus[2];
                    Log.e(TAG, "    =" + currentSize + ",   =" + totalSize + ",status=" + status);
                    /*if(i++>100){
                        Log.e(TAG, "    =" + currentSize + ",   =" + totalSize + ",status=" + status);
                        i=0;
                    }*/
                    //     ,onChange        ,        
                    logStatus(status);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private boolean doSuccess=false;
    private void logStatus(int status) {
        switch (status) {
            //      
            case DownloadManager.STATUS_PENDING:
                Log.e(TAG, "queryUri: STATUS_PENDING");
                break;
            //    
            case DownloadManager.STATUS_PAUSED:
                Log.e(TAG, "queryUri: STATUS_PAUSED");
                break;
            //     
            case DownloadManager.STATUS_RUNNING:
                Log.e(TAG, "queryUri: STATUS_RUNNING");
                break;
            //     
            case DownloadManager.STATUS_SUCCESSFUL:
                Log.e(TAG, "queryUri: STATUS_SUCCESSFUL");
                if(!doSuccess){
                    doSuccess=true;
                    queryDownFileInfo();
                }
                break;
            //     
            case DownloadManager.STATUS_FAILED:
                Log.e(TAG, "queryUri: STATUS_FAILED");
                break;
            default:
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(observer);
    }
    
}
xml:
       
  참고 글:
1. Android DownloadManager 사용 ,버그
2, DownloadManager 구현 버 전 업데이트, 감청 다운로드 진행
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.