您的位置:首页 > 理论基础 > 计算机网络

从网络下载apk并自动安装

2015-10-14 19:42 756 查看
今天还学习了从网络下载apk并自动安装,其下载过程和之前的下载歌曲和图片的方法都是一样的,唯一的不同是我们要设置apk

下载完成之后要执行自动安装。

MainActivity:同样是传一个下载路径给Service

package com.example.text01;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

private String path = "http://10.17.152.88:8080/com.youxi.market2_v1.1.0_34.apk";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void download(View view){
Intent intent = new Intent(this, MyService.class);
intent.putExtra("path", path);
startService(intent);
}

}
创建一个类继承IntentService:

package com.example.text01;

import java.io.File;

import com.example.http.ExternalStorageUtils;
import com.example.http.HttpUtils;

import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class MyService extends IntentService {

public MyService(String name) {
super(name);

}

public MyService() {
super("");
}

@Override
protected void onHandleIntent(Intent intent) {
String path = intent.getStringExtra("path");
String name = path.substring(path.lastIndexOf("/") + 1);
if (HttpUtils.isNetWorkConn(MyService.this)) {
byte[] data = HttpUtils.getByteArray(path);
if (data != null && data.length != 0) {
boolean flag = ExternalStorageUtils.writeExternalStorageRoot(
name, data, MyService.this);
if (flag) {
Log.i("main", "下载成功,即将安装");
// 下载成功--》自动安装
Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_VIEW);
// 获取文件路径
File file = new File(
Environment.getExternalStorageDirectory(), name);
// Uri uri = Uri.parse(file.getAbsolutePath());
Uri uri = Uri.fromFile(file);
// 打开apk
intent2.setDataAndType(uri,
"application/vnd.android.package-archive");
// 设置启动模式
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
} else {
Log.i("main", "文件保存失败");
}
}
}
}

}
下面是HttpUtils工具类:

package com.example.http;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.Entity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtils {
//判断网络连接状态
public static boolean isNetWorkConn(Context context){
boolean flag = false;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.isConnected();
}
return flag;
}
//把网址中的数据解析到字节数组中
public static byte[] getByteArray(String path){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
try {
HttpResponse res = client.execute(get);
if (res.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toByteArray(res.getEntity());
}
} catch (ClientProtocolException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
return null;
}
}
然后是写入文件的工具类:

package com.example.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class ExternalStorageUtils {

//判断sdCard是否可用
public static boolean isSdcardUseful(){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
}
return false;
}
//存储内容
public static boolean writeExternalStorageRoot(String name,byte[] data,Context context){
if (isSdcardUseful()) {
//获取sdCard的根目录
File sdFile = Environment.getExternalStorageDirectory();
//创建文件的抽象路径
File file = new File(sdFile, name);
//向文件中写数据
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data, 0, data.length);
fos.flush();
fos.close();
//返回true
return true;
} catch (Exception e) {

e.printStackTrace();
}
}else{
Log.i("main", "sdCard不可用");
}
return false;
}
//读取外部存储中根目录的文件
public static byte[] readExternalStorageRoot(String fileName){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (isSdcardUseful()) {
File sdFile = Environment.getExternalStorageDirectory();
File file = new File(sdFile, fileName);
if (file.exists()) {
//读取文件
try {
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
baos.write(buffer, 0, len);
baos.flush();
}
fis.close();
return baos.toByteArray();
} catch (Exception e) {

e.printStackTrace();
}
}else{
Log.i("main", "文件不存在");
}
}
return null;
}
//直接获取Bitmap的形式返回
public static Bitmap readExternalStorageRootToBitmap(String fileName){
Bitmap bitmap = null;
if (isSdcardUseful()) {
File file = new File(Environment.getExternalStorageDirectory(), fileName);
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
return bitmap;
}
}
最后在清单文件中加入权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: