Android 서비스 다운로드 파일 구현,Notification 다운로드 진행 예시 표시

gif 부터 넣 어.최종 효과:

주로 Android 가 서버 에서 파일 을 다운로드 하고 Notification 을 호출 하여 다운로드 진 도 를 표시 하 며 다운로드 가 끝 난 후에 알림 을 누 르 면 APK 를 설치 하 는 인터페이스 로 이동 합 니 다.프레젠테이션 은 실제 네트워크 환경 에서 실제 URL 로 프레젠테이션 을 하고 코드 를 보 여 줍 니 다.
MainActivity 코드 는 매우 간단 합 니 다.바로 Service 를 시작 하 는 것 입 니 다.

public class MainActivity extends AppCompatActivity {
 String download_url="http://shouji.360tpcdn.com/160329/a9037075b8d3aa98fbf6115c54a5b895/com.alensw.PicFolder_4722404.apk";

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

 }
 public void bt_start_service(View view){
  Intent intent=new Intent(this,DownLoadService.class);
  intent.putExtra("download_url",download_url);
  startService(intent);
 }
}

DownloadService 에 서 는 onStartCommand 방법 에서 핵심 코드 입 니 다.Notify Util 이라는 도구 류 의"notify"를 호출 합 니 다.progress"방법 은 알림 을 표시 하 는 동시에 APK 파일 을 다운로드 하기 시작 합 니 다.DownloadService 코드 는 다음 과 같 습 니 다.

public class DownLoadService extends Service {
 String download_url;
 String savePath= Environment.getExternalStorageDirectory()+"/liulan.apk";
 private int requestCode = (int) SystemClock.uptimeMillis();
 private NotifyUtil currentNotify;
 File mFile;
 @Nullable
 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }

 @Override
 public void onCreate() {
  super.onCreate();


 }

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  mFile=new File(savePath);
  download_url=intent.getStringExtra("download_url");
  Log.e("test","  onStartCommand");
  //           
  Intent intent_noti = new Intent();
  intent_noti.setAction(Intent.ACTION_VIEW);
  //     , tomcat   
  intent_noti.setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive");
  PendingIntent rightPendIntent = PendingIntent.getActivity(this,
    requestCode, intent_noti, PendingIntent.FLAG_UPDATE_CURRENT);
  int smallIcon = R.drawable.xc_smaillicon;
  String ticker = "        ";
  //      ,      
  NotifyUtil notify7 = new NotifyUtil(this, 7);
  notify7.notify_progress(rightPendIntent, smallIcon, ticker, "        ", "     ",
    false, false, false, download_url, savePath, new NotifyUtil.DownLoadListener() {
     @Override
     public void OnSuccess(File file) {
      mFile=file;
      DownLoadService.this.stopSelf();
     }

     @Override
     public void onFailure(Throwable t, int errorNo, String strMsg) {

     }
    });
  currentNotify = notify7;
  return super.onStartCommand(intent, flags, startId);

 }
}

"notify"호출 중progress'방법 때 이미 파일 을 다운로드 하기 시 작 했 습 니 다.그러면 다운로드 코드 는 무엇 입 니까?다음 과 같다.

public void notify_progress(PendingIntent pendingIntent, int smallIcon,
        String ticker, String title, String content,
        boolean sound, boolean vibrate, boolean lights,
        String download_url, String savePath, final DownLoadListener listener) {

  setCompatBuilder(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights);
  /*
   *                           ,             。
   *        ,        。                 。
   */
  FinalHttp fh = new FinalHttp();
  HttpHandler<File> httpHandler=fh.download(download_url, savePath, new AjaxCallBack<File>() {
   @Override
   public void onLoading(long count, long current) {
    super.onLoading(count, current);
    double a=count;
    double b=current;
    double currentPro=(double)((b/a)*100);
    cBuilder.setProgress(100, (int)currentPro, false);
    sent();
   }

   @Override
   public void onSuccess(File file) {
    super.onSuccess(file);
    cBuilder.setContentText("    ").setProgress(0, 0, false);
    sent();
    listener.OnSuccess(file);
   }

   @Override
   public void onFailure(Throwable t, int errorNo, String strMsg) {
    super.onFailure(t, errorNo, strMsg);
    listener.onFailure(t,errorNo,strMsg);
   }

  });


 }

여기 썼어 요afinal.jar
이 jar 는 다운로드 한 도구 류 를 봉 인 했 습 니 다.직접 가 져 와 서 사용 하면 됩 니 다.다운로드 에 성공 하면 DownloadListener 라 는 인 터 페 이 스 를 통 해 DownloadService 로 되 돌 립 니 다.최종 실행 효 과 는 맨 위 에 있 는 gif 동적 그림 실행 효과 와 같 습 니 다.
프로젝트 다운로드 주소:다운로드 클릭
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기