35 Android 在线安装APK



HttpUtils 工具类:

package com.example.android_apk_install;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.http.HttpResponse;
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 org.json.JSONObject;

import android.os.Environment;

public class HttpUtils {

	public HttpUtils()
	{
		
	}
	public static String getMessage(String path)
	{
		String str=null;
		HttpClient httpClient=new DefaultHttpClient();
		HttpGet httpGet=new HttpGet(path);
		try {
			HttpResponse response=httpClient.execute(httpGet);
			if(response.getStatusLine().getStatusCode()==200)
			{
				String jsonStr=EntityUtils.toString(response.getEntity());
				JSONObject jsonObject=new JSONObject(jsonStr);
				str=jsonObject.getString("versionname");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			httpClient.getConnectionManager().shutdown();
		}
		return str;
	}
	
	
	/**
	 * 得到APK数据,存到 sdcard卡
	 * @param path
	 * @return 返回路径
	 */
	public static  String downLoadAPK(String path)
	{
		byte[] data=null;
		HttpClient httpClient =new DefaultHttpClient();
		File file=Environment.getExternalStorageDirectory();
		FileOutputStream outputStream=null;
		HttpGet httpGet=new HttpGet(path);
		try {
			HttpResponse response=httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode()==200) {
				data=EntityUtils.toByteArray(response.getEntity());
				
				if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					//名称需处理
					outputStream=new FileOutputStream(new File(file, "abc.apk"));
					outputStream.write(data, 0, data.length);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(outputStream != null)
			{
				try {
					outputStream.close();
					
				} catch (Exception e2) {
					// TODO: handle exception
					e2.printStackTrace();
				}
			}
		}
		return file.getAbsolutePath()+"/"+"abc.apk" ;
		
		
	}
}


PackageUtils 工具类

package com.example.android_apk_install;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
 * 版本信息
 * @author Administrator
 *
 */
public class PackageUtils {
	private Context context;
	private PackageManager manager;
	private PackageInfo info;

	public PackageUtils(Context context) {
		this.context = context;
		init();
	}

	/**
	 * 初始化数据
	 */
	public void init() {
		manager = context.getPackageManager();
		try {
			info = manager.getPackageInfo(context.getPackageName(),
					PackageManager.GET_ACTIVITIES);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
	
	public int getVersionCode()
	{
		return info.versionCode;
	}
	/**
	 * 
	 * @return
	 */
	public String getVersionName()
	{
		return info.versionName;
	}
	/**
	 * 是否需要升级
	 * @param oldVersion
	 * @param newVersion
	 * @return
	 */
	public boolean isUpgrada(int oldVersion,int newVersion)
	{
		boolean flag = false;
		flag = newVersion > oldVersion ? true : false;
		return flag;
	}
}

加权限:

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

MainActivity.java代码:

package com.example.android_apk_install;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
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.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	PackageUtils utils;
	private ProgressDialog dialog;
	private AlertDialog.Builder builder;
	private String path="http://........................";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		builder=new AlertDialog.Builder(this);
		builder.setTitle(" 提示");
		builder.setMessage("有新的版本,是否现在更新");
		builder.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		utils=new PackageUtils(this);
		int currVersionCode=utils.getVersionCode();
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示");
		dialog.setMessage("Loading...");
		//执行异步任务
		try {
			new MyTask().execute(path).get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public class DownLoadAPK extends AsyncTask< String, Void, Void>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String pathStr=HttpUtils.downLoadAPK(params[0]);
			System.out.println("---->>"+pathStr);
			if(pathStr != null)
			{
				//"/mnt/sdcard//abc.apk"
				Uri uri=Uri.fromFile(new File(pathStr));
				Intent intent=new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, "application/vnd.android.package-archive");
				startActivity(intent);
				
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}
		
	}
	
	/**
	 * 是否提示下载更新
	 * @author Administrator
	 *
	 */
	class MyTask extends AsyncTask<String, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			//调用
			return HttpUtils.getMessage(params[0]);
		
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android 11引入了一些新的安全限制,影响了应用程序安装apk的接口。在Android 11及更高版本中,应用程序只能使用特定的安装接口来安装apk文件,以提高应用程序的安全性。 新的安装接口是PackageInstaller类的install方法。要安装apk文件,应用程序需要以下步骤: 1. 获取PackageInstaller的实例。可以使用PackageManager的getPackageInstaller方法来获得。 2. 创建一个新的会话(Session)。会话将用于安装apk文件。 3. 为这个会话创建一个安装包信息(PackageInstallParams)对象。可以设置apk文件的路径、标记等信息。 4. 调用PackageInstaller的createSession方法,传入PackageInstallParams对象,以创建一个新的安装会话。 5. 打开会话,可以使用openWrite方法来获取一个OutputStream对象,将apk文件写入该流中。 6. 当apk文件写入完毕后,关闭输出流。然后调用commit方法提交会话。 7. 应用程序可以监听会话的状态变化,以获得安装的进度和结果。 除了使用新的接口,Android 11还引入了一些权限限制。应用程序需要请求特定的权限来安装apk文件,如WRITE_EXTERNAL_STORAGE权限。此外,应用程序还需要声明REQUEST_INSTALL_PACKAGES权限,以使用PackageInstaller接口。 需要注意的是,通过使用PackageInstaller接口进行安装apk文件将被视为"分离的"安装,它们的应用数据会被隔离,不会与安装apk的应用程序共享。这意味着,通过PackageInstaller安装的应用无法直接在应用列表中找到,只能通过系统的设置->应用->特定应用来卸载。 总而言之,Android 11引入了一些安全限制,改变了应用程序安装apk的接口。应用程序需要使用新的PackageInstaller接口,并获取特定的权限才能安装apk文件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值