Android 网络应用重点———使用HttpGet 下载apk文件并安装

本文介绍如何使用HttpGet从服务器端下载apk文件,并自动将其安装到手机上。通过实现下载文件原理和安装apk的具体代码,展示了一个完整的流程。在实际应用中,需先运行服务器端oa工程并输入指定URL查看效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 本例使用HttpGet 从服务器端下载一个apk文件,然后自动将apk安装到手机上
下载文件原理: 先获得一个InputStream,读取到数据,再写入到目的地(通常写到SD卡), 概括起来也就是先读再写
主要代码如下:
public class Main extends Activity implements OnClickListener
{
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main); 
  Button btnDownloadInstallApk = (Button) findViewById(R.id.btnDownloadInstallApk);
  btnDownloadInstallApk.setOnClickListener(this);
 } 
 //安装apk文件
 private void installApk(String filename)
 {
  File file = new File(filename);
  Intent intent = new Intent();
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  intent.setAction(Intent.ACTION_VIEW);     //浏览网页的Action(动作)
  String type = "application/vnd.android.package-archive";
  intent.setDataAndType(Uri.fromFile(file), type);  //设置数据类型
  startActivity(intent);
 }
 @Override
 public void onClick(View view)
 {
  //下载文件  存放目的地
  String downloadPath = Environment.getExternalStorageDirectory().getPath() + "/download_cache";  
  String url = "http://192.168.1.123/oa/apk/action.apk";
  File file = new File(downloadPath);
  if(!file.exists())
   file.mkdir();
  HttpGet httpGet = new HttpGet(url);
  try
  {
   HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
   if (httpResponse.getStatusLine().getStatusCode() == 200)
   {
    InputStream is = httpResponse.getEntity().getContent();
    // 开始下载apk文件
    FileOutputStream fos = new FileOutputStream(downloadPath + "/action.apk");
    byte[] buffer = new byte[8192];
    int count = 0;
    while ((count = is.read(buffer)) != -1)
    {
     fos.write(buffer, 0, count);
    }
    fos.close();
    is.close();
    //安装  apk 文件
    installApk(downloadPath+ "/action.apk");
   }
  } catch (Exception e){}
 }
}

示意图

1.  2. 

3.4.
 具体代码请参见 ch09_remoteinstallapk工程,在这里要先运行服务器端oa工程,可以输入http://192.168.1.123/oa/apk/action.apk看看效果

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值