源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android 基于IntentService的文件下载的示例代码

  • 时间:2021-03-20 04:02 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android 基于IntentService的文件下载的示例代码
文件下载这种事情是很耗时的。之前使用AsyncTask这样的异步类来做下载,然后切到后台就被干掉。所以打算试试Service。(不过按目前那些系统的尿性,其实Service也分分钟被干掉) 不过,这里并不是直接使用Service类,而是使用的是继承自Service的IntentService。 这个东西有三大好处: 1.他有个任务队列; 2.任务队列执行完后会自动停止; 3.他会起一个独立的线程,耗时操作不会影响你app的主线程。 这么自动化的东西简直省心。 话不多说,开始撸代码。 首先,要建个应用,主文件如下(布局什么的代码就不贴了):
package net.codepig.servicedownloaderdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
  private String _url="http://www.boosj.com/apk/boosjDance.apk";
  private EditText urlText;
  private Button goBtn;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    goBtn=(Button) findViewById(R.id.goBtn);
    urlText=(EditText) findViewById(R.id.urlText);
    urlText.setText(_url);
    goBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        _url=urlText.getText().toString();
        //start download
        start_service();
      }
    });
  }

  public void start_service(){
    //等会再填
  }
}

以上代码不重要,嗯。 接下来是重点。创建一个IntentService 类,然后重写他的onHandleIntent 。 需要执行的任务就写在onHandleIntent 里 这里先用Thread.sleep模拟一下耗时任务,试跑一下就可以看到主app关闭后service还在跑,跑完后就自己Destroy了。
package net.codepig.servicedownloaderdemo;

import android.app.IntentService;
import android.content.Intent;

/**
 * 下载服务
 * Created by QZD on 2017/9/20.
 */

public class DownLoadService extends IntentService {
  public DownLoadService() {
    super("DownLoadService");//这就是个name
  }

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

  protected void onHandleIntent(Intent intent) {
    Bundle bundle = intent.getExtras();
    String downloadUrl = bundle.getString("download_url");

    Log.d(TAG,"下载启动:"+downloadUrl);
    Thread.sleep(1_000);
    int count=0;
    while(count<20){
      count++;
      Log.d(TAG,"下载运行中--"+count);
      Thread.sleep(1000);
    }
    Log.d(TAG,"下载结束");
  }

  @Override
  public void onDestroy() {
    Log.d(TAG, "onDestroy");
    super.onDestroy();
  }
}

通过Intent接收任务,这里在MainActivity中通过startService启动服务
public void start_service(){
    Intent intent=new Intent(this,DownLoadService.class);
    intent.putExtra("download_url",_url);
    startService(intent);
  }
当然,AndroidManifest.xml里也得注册上
[url=https://github.com/codeqian/serviceDownloaderDemo]serviceDownloaderDemo [/url] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部