Service、IntentService下载Apk

1.Service下载的APK(已验证)

Service类

public class DownloadService extends Service {

    /**
     * 安卓系统下载类
     **/
    DownloadManager manager;

    /**
     * 接收下载完的广播
     **/
    DownloadCompleteReceiver receiver;

    /**
     * 初始化下载器
     **/
    private void initDownManager() {

        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

        receiver = new DownloadCompleteReceiver();

        //设置下载地址
        DownloadManager.Request down = new DownloadManager.Request(
                Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));

        // 设置允许使用的网络类型,这里是移动网络和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);

        // 下载时,通知栏显示途中
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);

        // 显示下载界面
        down.setVisibleInDownloadsUi(true);

        // 设置下载后文件存放的位置
        down.setDestinationInExternalFilesDir(this,
                Environment.DIRECTORY_DOWNLOADS, "baidumusic.apk");

        // 将下载请求放入队列
        manager.enqueue(down);

        //注册下载广播
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 调用下载
        initDownManager();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        // 注销下载广播
        if (receiver != null)
            unregisterReceiver(receiver);
        super.onDestroy();
    }

    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {

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

            //判断是否下载完成的广播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                //获取下载的文件id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                //自动安装apk
                installAPK(manager.getUriForDownloadedFile(downId));//dManager.getUriForDownloadedFile(myDwonloadID);
                //停止服务并关闭广播
                stopSelf();
            }
        }

        /**
         * 安装apk文件
         */
        private void installAPK(Uri downloadFileUri) {
            Intent intents = new Intent();
            intents.setAction(Intent.ACTION_VIEW);
            intents.setData(downloadFileUri);
            intents.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intents);
        }
    }
}

Actiivity

public class ApkActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent mIntent = new Intent(this,DownloadService.class);
        startService(mIntent);
    }
}

AndroidManifest.xml注册service:

<service   
          android:name="com.example.test.UpdataService"  
          android:enabled="true"  
          >  
      </service> 
添加的权限
<uses-permission android:name="android.permission.INTERNET" />  
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />  

2. IntentService下载(已验证)

public class DownloadIntentService extends IntentService {


    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public DownloadIntentService(String name) {
        super(name);
    }

    public DownloadIntentService() {
        super("test-intentService");
    }

    private NotificationManager notificationManager;
    private Notification notification;
    private RemoteViews rViews;
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle bundle = intent.getExtras();
        // 获得下载文件的url
        String downloadUrl = bundle.getString("url");
        // 设置文件下载后的保存路径,保存在SD卡根目录的Download文件夹
        File dirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download");
        // 检查文件夹是否存在,不存在则创建
        if (!dirs.exists()) {
            dirs.mkdir();
        }
        File file = new File(dirs, "file.apk");
        // 设置Notification
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification(R.drawable.ic_launcher, "版本更新下载", System.currentTimeMillis());
        Intent intentNotifi = new Intent(this, ApkActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentNotifi, 0);
        notification.contentIntent = pendingIntent;
        // 加载Notification的布局文件
        rViews = new RemoteViews(getPackageName(), R.layout.downloadfile_layout);
        // 设置下载进度条
        rViews.setProgressBar(R.id.downloadFile_pb, 100, 0, false);
        notification.contentView = rViews;
        notificationManager.notify(0, notification);
        // 开始下载
        downloadFile(downloadUrl, file);
        // 移除通知栏
        notificationManager.cancel(0);
        // 广播出去,由广播接收器来处理下载完成的文件
        Intent sendIntent = new Intent("com.test.downloadComplete");
        // 把下载好的文件的保存地址加进Intent
        sendIntent.putExtra("downloadFile", file.getPath());
        sendBroadcast(sendIntent);
    }
    private int fileLength, downloadLength;

    public void onDestroy() {
        // 移除定時器
        handler.removeCallbacks(run);
        super.onDestroy();
    }

    // 定时器,每隔一段时间检查下载进度,然后更新Notification上的ProgressBar
    private Handler handler = new Handler();
    private Runnable run = new Runnable() {
        public void run() {
            rViews.setProgressBar(R.id.downloadFile_pb, 100, downloadLength*100 / fileLength, false);
            notification.contentView = rViews;
            notificationManager.notify(0, notification);
            handler.postDelayed(run, 1000);
        }
    };

    private void downloadFile(String downloadUrl, File file){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
//            Log.e(TAG, "找不到保存下载文件的目录");
            e.printStackTrace();
        }
        InputStream ips = null;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            huc.setReadTimeout(10000);
            huc.setConnectTimeout(3000);
            fileLength = Integer.valueOf(huc.getHeaderField("Content-Length"));
            ips = huc.getInputStream();
            // 拿到服务器返回的响应码
            int hand = huc.getResponseCode();
            if (hand == 200) {
                // 开始检查下载进度
                handler.post(run);
                // 建立一个byte数组作为缓冲区,等下把读取到的数据储存在这个数组
                byte[] buffer = new byte[8192];
                int len = 0;
                while ((len = ips.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    downloadLength = downloadLength + len;
                }
            } else {
//                Log.e(TAG, "服务器返回码" + hand);
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (ips != null) {
                    ips.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
public class ApkActivity extends Activity {

    BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = "http://www.appchina.com/market/d/1603385/cop.baidu_0/com.google.android.apps.maps.apk";
        Intent downloadIntent = new Intent(this, DownloadIntentService.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        downloadIntent.putExtras(bundle);
        startService(downloadIntent);
        // 设置广播接收器,当新版本的apk下载完成后自动弹出安装界面
        IntentFilter intentFilter = new IntentFilter("com.test.downloadComplete");
        receiver = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                Intent install = new Intent(Intent.ACTION_VIEW);
                String pathString = intent.getStringExtra("downloadFile");
                install.setDataAndType(Uri.fromFile(new File(pathString)), "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            }
        };
        registerReceiver(receiver, intentFilter);
    }


    protected void onDestroy() {
        // 移除广播接收器
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }
}
AndroidManifest.xml注册service:
 <service android:name=“.downloadApk.DownloadIntentService"/>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值