android 从服务器上获取APK下载安装
2013-06-18 16:37
447 查看
简单的为新手做个分享。
网上有些资料,不过都是很零散,或是很乱的,有的人说看不懂。一直有新手说做到服务器更新APK时没有思路,这里做个简单的分享,希望有不同思路的可以讨论。
下面做个很简单的读取处理和讲解思路。代码带有注释:
以上是读取APK文件并保存在了本地,InputStream转为FileOutputStream保存HttpURLConnection获取到的数据。
那么只要再找到你的那个保存的路径就能实现安装了。
下面是安装和卸载的代码:首先说下卸载:
UripackageURI=Uri.parse("package:com.demo.DUJINYANG");
IntentuninstallIntent=newIntent(Intent.ACTION_DELETE,packageURI);
startActivity(uninstallIntent);
Environment拥有一些可以获取环境变量的方法package:com.demo.DUJINYANG这个形式是package:程序完整的路径(包名+程序名).
然后是--安装:
Stringstr="/Dujinyang.apk";//APK的名字
StringfileName=Environment.getExternalStorageDirectory()+str;//我们上面说到路径
Intentintent=newIntent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(newFile(fileName)),
"application/vnd.android.package-archive");
startActivity(intent);
privatevoidopenFiles(Filefile){
//TODOAuto-generatedmethodstub
Intentintent=newIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
protectedFiledownLoadFile(StringhttpUrl){
finalStringfileName="dujinyang.apk";
FiletmpFile=newFile("/sdcard/update");
if(!tmpFile.exists()){
tmpFile.mkdir();//创建文件夹
}
finalFilefile=newFile("/sdcard/update/"+fileName);
try{
URLurl=newURL(httpUrl);
try{
HttpURLConnectionconn=(HttpURLConnection)url
.openConnection();
InputStreamis=conn.getInputStream();
FileOutputStreamfileOutput=newFileOutputStream(file);
byte[]buf=newbyte[256];//分配byte
conn.connect();
doublecount=0;
if(conn.getResponseCode()>=400){
Toast.makeText(Main.this,"连接超时",Toast.LENGTH_SHORT)
.show();
}else{
while(count<=100){
if(is!=null){
intnumRead=is.read(buf);
if(numRead<=0){
break;
}else{
fileOutput.write(buf,0,numRead);
}
}else{
break;
}
}
}
conn.disconnect();//需要记得关闭连接
fileOutput.close();
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}catch(MalformedURLExceptione){ e.printStackTrace();
}
returnfile;
}
到这里思路简单的理清完了。
此时可以根据你自身的项目去整改。如果新手还有不懂的可以私聊。
--分享希望大家有好的代码可以分享,共同讨论
相关文章推荐
- android 从服务器上获取APK下载安装
- android 从服务器上获取APK并下载安装
- Android - 代码的组织方式,splash界面,获取应用的版本号,获取服务器版本号,下载安装apk,跑马灯效果
- android 从服务器上获取APK下载安装
- android 从服务器上获取APK下载安装
- android 从服务器上获取APK下载安装
- android 从服务器上获取APK下载安装
- Android----- 版本更新和 服务器下载新版本APK并安装
- android从服务器获取apk安装
- Android实现检查并下载APK更新、安装APK及获取网络信息的方法
- Android----- 版本更新和 服务器下载新版本APK并安装
- Android----- 版本更新和 服务器下载新版本APK并安装
- android apk下载完成后调用安装
- Android apk下载 安装 卸载 打开
- APK 变成 ZIP:Android 手机应用程序文件下载服务器需要注意的问题
- 【Android】获取手机中已安装apk文件信息(PackageInfo、ResolveInfo)(应用图片、应用名、包名等)
- Android 下载安装APK
- android获取未安装的APK文件的信息
- 关于android中版本自动更新,从服务器下载下来的文件不能安装的问题
- 【Android】获取手机中已安装apk文件信息(PackageInfo、ResolveInfo)(应用图片、应用名、包名等)