您的位置:首页 > 移动开发 > Android开发

android下载apk并安装

2015-06-25 11:38 423 查看
直接上代码

方案一:没测试过是否可用

File file;

private Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what) {

case 1:

installApk();

break;

}

}

};

/**

* 后台在下面一个Apk 下载完成后返回下载好的文件

*

* @param httpUrl

* @return

*/

private File downFile(final String httpUrl) {

new Thread(new Runnable() {

@Override

public void run() {

try {

URL url = new URL(httpUrl);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setConnectTimeout(5000);

FileOutputStream fileOutputStream = null;

InputStream inputStream;

if (connection.getResponseCode() == 200) {

inputStream = connection.getInputStream();

if (inputStream != null) {

file = getFile(httpUrl);

fileOutputStream = new FileOutputStream(file);

byte[] buffer = new byte[1024];

int length = 0;

while ((length = inputStream.read(buffer)) != -1) {

fileOutputStream.write(buffer, 0, length);

}

fileOutputStream.close();

fileOutputStream.flush();

}

inputStream.close();

}

System.out.println("已经下载完成");

// 往handler发送一条消息 更改button的text属性

Message message = handler.obtainMessage();

message.what = 1;

handler.sendMessage(message);

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}).start();

return file;

}

/**

* 安装APK

*/

private void installApk() {

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

startActivity(intent);

}

@Override

protected void onStart() {

super.onStart();

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);

intentFilter.addDataScheme("package");

// 注册一个广播

registerReceiver(broadcastReceiver, intentFilter);

}

@Override

protected void onDestroy() {

super.onDestroy();

// 解除广播

unregisterReceiver(broadcastReceiver);

}

/**

* 根据传过来url创建文件

*

*/

private File getFile(String url) {

File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url));

return files;

}

/**

* 截取出url后面的apk的文件名

*

* @param url

* @return

*/

private String getFilePath(String url) {

return url.substring(url.lastIndexOf("/"), url.length());

}

///////////jni

public void versionUpdate(String url)

{

downFile(url);

}

配置文件中添加访问往sd卡写文件的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission></uses-permission>

方案二:项目中用到的

public static String UCAPK="";

public static void backDownload(String url)//UC后台下载

{

UCAPK = getFilePath(url);

Log.d("cocos2d-x debug info", "BUG ... "+UCAPK);

Log.d("cocos2d-x debug info", "BUG HERE ... "+1);

//DownloadReceiver.receiverParam(context, UCAPK);

manager = (DownloadManager)context.getSystemService(context.DOWNLOAD_SERVICE);

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

//设置可用的网络类型

request.setAllowedNetworkTypes(request.NETWORK_MOBILE | request.NETWORK_WIFI);

request.setAllowedOverRoaming(false);

request.setDestinationInExternalPublicDir("/download/", UCAPK);

//将下载请求放入队列

long UCID = manager.enqueue(request);

//注册监听

//DownloadReceiver receiver = new DownloadReceiver();

context.registerReceiver(receiver, new IntentFilter(manager.ACTION_DOWNLOAD_COMPLETE));

Log.d("cocos2d-x debug info", "BUG HERE ... "+10);

}

private static BroadcastReceiver receiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

Log.d("cocos2d-x debug info", "into listen ... ");

//queryDownloadStatus();

if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

File uc= new File(Environment.getExternalStoragePublicDirectory("/download/"),UCAPK);

installApk(uc);

}

}

};

//下载完成安装APK

public static void installApk(File file) {

Log.d("cocos2d-x debug info", "BUG HERE ... "+12);

Intent intent = new Intent();

intent.setAction("android.intent.action.VIEW");

intent.addCategory("android.intent.category.DEFAULT");

intent.setType("application/vnd.android.package-archive");

intent.setData(Uri.fromFile(file));

intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

context.startActivity(intent);

Log.d("cocos2d-x debug info", "BUG HERE ... "+13);

}

/**

* 截取出url后面的apk的文件名

*

* @param url

* @return

*/

private String getFilePath(String url) {

return url.substring(url.lastIndexOf("/"), url.length());

}

另外补充下,由于java这不是很熟,主要弄cocos2dx这块, 看了下需求中涉及到的java广播的注册

注册主要分为两种:常驻型和非常驻型,常驻型就是在mainfest.xml中添加的,在关闭程序后仍可接收;非常驻型要再代码中注册和解除,像代码一中那样,关闭程序后接收不到广播。而方法二的方法中不需要在onStart()和onDestroy()中注册和解除,亲测在关闭程序后收不到下载完成后的广播。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 下载 apk 安装