1

다운로드 관리자를 사용하여 apk를 다운로드하여 내 앱을 업데이트하려고합니다. 나는 을 듣고 MainActivity에 방송 수신기를 등록하고 onReceive 방법으로 APK를 엽니 다.DownloadManager를 사용하여 앱 전체에서 Android 업데이트 앱을 다시 시작합니다 (여러 번 다운로드하지 않기).

public class MainActivity extends CordovaActivity { 
private long downloadReference; 
private DownloadManager downloadManager; 
private IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); 

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

    registerReceiver(downloadReceiver, intentFilter); 

} 

public void updateApp(String url) { 
    //start downloading the file using the download manager 
    downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
    Uri Download_Uri = Uri.parse(url); 
    DownloadManager.Request request = new DownloadManager.Request(Download_Uri); 
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); 
    request.setAllowedOverRoaming(false); 
    request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, "myapk.apk"); 
    downloadReference = downloadManager.enqueue(request); 
} 


@Override 
public void onDestroy() { 
    //unregister your receivers 
    this.unregisterReceiver(downloadReceiver); 
    super.onDestroy(); 
} 

private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     //check if the broadcast message is for our Enqueued download 
     long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); 
     if (downloadReference == referenceId) { 

      //start the installation of the latest version 
        Intent installIntent = new Intent(Intent.ACTION_VIEW); 
       installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(downloadReference), 
         "application/vnd.android.package-archive"); 
       installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       context.startActivity(installIntent); 

     } 

    } 

}; 

} 

updateApp(url)이 UI에 버튼의 클릭에 호출됩니다 다음은 코드입니다. 버튼을 클릭하면 다운로드가 시작됩니다. 다운로드가 시작된 후 응용 프로그램이 닫혔다는 것을 나타냅니다 (수신기가 등록되지 않음). 응용 프로그램이 다시 시작될 때 두 가지 시나리오에 문제가 있습니다. downloadReference
이 손실되고 내 수신기가 방송을 수신 할 때 referenceId 실 거예요, 그래서 installIntent이 시작되지 않습니다 downloadReference과 같아야 - 내 응용 프로그램이 다시 시작된 후

  1. 이전의 다운로드가 완료됩니다. 그래서 업데이트 버튼을 다시 클릭하고 다운로드를 시작해야합니다. 이 문제를 피할 수있는 방법이 있습니까?

  2. 내 앱이 다시 시작되기 전에 이전 다운로드가 완료되었습니다. - 새로 시작한 활동 인 에서 이전 다운로드가 완료되었음을 알 수있는 방법이 없습니다. 다시 버튼을 클릭하고 다운로드를 다시 시작해야합니다. 다운로드 관리자 용으로 끈적 거리는 브로드 캐스트를 사용하도록 설정하는 방법이 있습니까?

답변

0

이렇게하려면 원하는대로 다운로드 참조를 저장해야합니다. 그런 다음 DownloadManager.Query()을 사용하여 DownloadManager를 쿼리하면 앱에 의해 DownloadManager에 게시 된 모든 다운로드 요청을 포함하는 커서가 반환됩니다. 그런 다음 downloadReference ID를 일치시킨 다음 다운로드 상태를 확인할 수 있습니다. 완료되면 DownloadManager.COLUMN_LOCAL_FILENAME에서 경로를 가져올 수 있습니다.

private void updateDownloadStatus(long downloadReference) {  
    DownloadManager.Query query = new DownloadManager.Query(); 

    // if you have stored the downloadReference. Else you have to loop through the cursor. 
    query.setFilterById(downloadReference); 

    Cursor cursor = null; 

    try { 
    cursor = DOWNLOAD_MANAGER.query(query); 
    if (cursor == null || !cursor.moveToFirst()) { 
     // restart download 
     return; 
    } 
    float bytesDownloaded = 
     cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); 
    float bytesTotal = 
     cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); 
    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS); 
    int downloadStatus = cursor.getInt(columnIndex); 
    int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON); 
    int failureStatus = cursor.getInt(columnReason); 
    int filePathInt = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME); 
    String filePath = cursor.getString(filePathInt); 

    switch (downloadStatus) { 
     case DownloadManager.STATUS_FAILED: 
     case DownloadManager.ERROR_FILE_ERROR: 
     // restart download 
     break; 

     case DownloadManager.STATUS_SUCCESSFUL: 
     if (filePath != null) { 
      //got the file 
     } else { 
      //restart 
     } 
     break; 

     case DownloadManager.STATUS_PENDING: 
     case DownloadManager.STATUS_RUNNING: 
     case DownloadManager.STATUS_PAUSED: 
     /// wait till download finishes 
     break; 
    } 
    } catch (Exception e) { 
    Log.e("Error","message" + e.getMessage(), e); 
    } finally { 
    if (cursor != null) { 
     cursor.close(); 
    } 
    } 
} 
관련 문제