Androidダウンロードファイル通知バー進捗バー機能のインスタンスコードを表示

4880 ワード

1.AsyncTask非同期タスクインプリメンテーションを使用して、publishProgress()メソッドを呼び出して進捗状況をリフレッシュしてインプリメンテーション(最適化)する

public class MyAsyncTask extends AsyncTask {
  private Context context;
  private NotificationManager notificationManager;
  private NotificationCompat.Builder builder;
  public MyAsyncTask(Context context){
    this.context = context;
    notificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(context);
  }
  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    builder.setSmallIcon(R.mipmap.ic_launcher)
        .setContentInfo("   ...")
        .setContentTitle("    ");
  }
  @Override
  protected Integer doInBackground(String... params) {
    Log.e(TAG, "doInBackground: "+params[0] );
    InputStream is = null;
    OutputStream os = null;
    HttpURLConnection connection = null;
    int total_length = 0;
    try {
      URL url1 = new URL(params[0]);
      connection = (HttpURLConnection) url1.openConnection();
      connection.setRequestMethod("GET");
      connection.setReadTimeout(50000);
      connection.connect();
      if(connection.getResponseCode() == 200){
        is = connection.getInputStream();
        os = new FileOutputStream("/sdcard/zongzhi.apk");
        byte [] buf = new byte[1024];
        int len;
        int pro1=0;
        int pro2=0;
        //        ,      
        long file_length = connection.getContentLength();
        while((len = is.read(buf))!=-1){
          total_length += len;
          if(file_length>0) {
            pro1 = (int) ((total_length / (float) file_length) * 100);//    (    )
          }
          if(pro1!=pro2) {
            //   update  ,    
            publishProgress(pro2=pro1);
          }
          os.write(buf, 0, len);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      try {
        if (is != null) {
          is.close();
        }
        if (os != null) {
          os.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (connection != null) {
        connection.disconnect();
      }
    }
    return total_length;
  }
  @Override
  protected void onCancelled(Integer integer) {
    super.onCancelled(integer);
  }
  @Override
  protected void onCancelled() {
    super.onCancelled();
  }
  @Override
  protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    builder.setProgress(100,values[0],false);
    notificationManager.notify(0x3,builder.build());
    //      
    builder.setContentText("  "+values[0]+"%");
    if(values[0]==100) {  //         
      Intent it = new Intent(Intent.ACTION_VIEW);
      it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      it.setDataAndType(Uri.parse("file:///sdcard/zongzhi.apk"), "application/vnd.android.package-archive");
      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
      builder.setContentTitle("    ")
          .setContentText("    ")
          .setContentInfo("    ")
          .setContentIntent(pendingIntent);
      notificationManager.notify(0x3, builder.build());
    }
  }
  @Override
  protected void onPostExecute(Integer integer) {
    super.onPostExecute(integer);
    if(integer == 100) {
      Toast.makeText(context, "    ", Toast.LENGTH_SHORT).show();
    }
  }
}

2、システムサービスを利用して実現する(特にこの方法を推奨しない)

//         
    DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    //        
    DownloadManager.Request request=new DownloadManager.Request(Uri.parse(downUrl));
    request.setDestinationInExternalPublicDir("  ","   ");
    request.setNotificationVisibility(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    downloadManager.enqueue(request);

まとめ
以上、編集者がご紹介したAndroidダウンロードファイル通知欄に進捗バー機能の実例コードが表示されていますので、ご協力をお願いします.