1.首先要添加权限,在AndroidManifest.xml添加如下权限:


 

2.在launcher的启动Activity的onCreate()方法中添加如下内容:

if (hasApk("com.tencent.android.qqdownloader")) {// install apk,
                //安装了apk
            }else { //no install apk
                ThreadPoolManager.getInstance().execute(new Runnable() {
                    
                    @Override
                    public void run() {
                        String oldPath = "/oem/etc/app/test.apk";   //原apk 所在位置
                        String newPath = getApplicationContext().getFilesDir().getAbsolutePath() + "/test.apk";  // 安装apk所在位置
                        //String newPath = "/data/data/com.example.contentprovidertest/files/test.apk";
                        deleteExistsFile(newPath); 
                        copyFile(oldPath , newPath);
                        boolean installApp = installApp(newPath,getPackageName());
                       
                        deleteExistsFile(newPath);
                       
                    }
                });
            }

            

private void deleteExistsFile(String path){
        File file = new File(path);
        if (file != null && file.exists()) {//delete file
            boolean delete = file.delete();
           
        }
    }
    
    private void copyFile(String oldPath, String newPath) {  
      
        //long currentTimeMillis = System.currentTimeMillis();
        try {   
            int bytesum = 0;   
            int byteread = 0;   
            File oldfile = new File(oldPath);   
            if (oldfile.exists()) { //文件存在时   
                FileInputStream inStream = new FileInputStream(oldPath); //读入原文件   
                FileOutputStream fs = new FileOutputStream(newPath);   
                byte[] buffer = new byte[1024*1024];   
           //     int length;   
                while ( (byteread = inStream.read(buffer)) != -1) {   
                    bytesum += byteread; //字节数 文件大小   
                    fs.write(buffer, 0, byteread); 
                    fs.flush();
                }   
                inStream.close();
                fs.close();
                fs = null;
                inStream = null;
                buffer = null;
            }   
        }   
        catch (Exception e) {   
            e.printStackTrace();   
   
        }   
       
    }
    
    private boolean installApp(String apkPath,String localPackageName) {
     
        //long currentTimeMillis = System.currentTimeMillis();
        
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install","-i",localPackageName, "-r", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
 
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
 
            }
            if (process != null) {
                process.destroy();
            }
        }
      
        //如果含有“success”单词则认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }
    
    private boolean hasApk(String packageName) {
        List installedPackages = getPackageManager().getInstalledPackages(0);
        for (int i = 0; i < installedPackages.size(); i++) {
            PackageInfo packageInfo = installedPackages.get(i);
            if (packageName.equals(packageInfo.packageName)) {
                return true;
            }
        }
        return false;
    }
    

 

ThreadPoolManager.java类:

public class ThreadPoolManager {  
    private static final String TAG = "ThreadPoolManager";
    /**  
     * 单例设计模式(饿汉式)  
     *  单例首先私有化构造方法,然后饿汉式一开始就开始创建,并提供get方法  
     */  
    private static ThreadPoolManager mInstance = new ThreadPoolManager();  
    public static ThreadPoolManager getInstance() {  
        return mInstance;  
    }  
  
    private int corePoolSize;//核心线程池的数量,同时能够执行的线程数量  
    private int maximumPoolSize;//最大线程池数量,表示当缓冲队列满的时候能继续容纳的等待任务的数量  
    private long keepAliveTime = 1;//存活时间  
    private TimeUnit unit = TimeUnit.SECONDS;  
    private ThreadPoolExecutor executor;  
    private ThreadPoolManager() {  
        /**  
         * 给corePoolSize赋值:当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行(有研究论证的)  
         */  
        corePoolSize = Runtime.getRuntime().availableProcessors()*2+1;
     
        maximumPoolSize = corePoolSize; //虽然maximumPoolSize用不到,但是需要赋值,否则报错  
        executor = new ThreadPoolExecutor(  
                corePoolSize, //当某个核心任务执行完毕,会依次从缓冲队列中取出等待任务  
                maximumPoolSize, //5,先corePoolSize,然后new LinkedBlockingQueue(),然后maximumPoolSize,但是它的数量是包含了corePoolSize的  
                keepAliveTime, //表示的是maximumPoolSize当中等待任务的存活时间  
                unit,   
                new LinkedBlockingQueue(), //缓冲队列,用于存放等待任务,Linked的先进先出  
                Executors.defaultThreadFactory(), //创建线程的工厂  
                new ThreadPoolExecutor.AbortPolicy() //用来对超出maximumPoolSize的任务的处理策略  
                );  
    }  
    /**  
     * 执行任务  
     */  
    public void execute(Runnable runnable){  
        if(runnable==null)return;  
  
        executor.execute(runnable);  
    }  
    /**  
     * 从线程池中移除任务  
     */  
    public void remove(Runnable runnable){  
        if(runnable==null)return;  
  
        executor.remove(runnable);  
    }  
}  
 

更多相关文章

  1. Android 线程超时的例子
  2. android Sqlite多线程访问异常解决方案
  3. android UI跨线程操作
  4. 在Android中实现多线程同步
  5. Android/java 多线程(五)-ThreadPoolExecutor线程池的使用
  6. Android 线程池来管理线程

随机推荐

  1. Android3.0自带天气例子
  2. MySQL处理JSON常见函数的使用
  3. MySQL和Python交互的示例
  4. mysql字符集相关总结
  5. mysql-canal-rabbitmq 安装部署超详细教
  6. 详解记录MySQL中lower_case_table_names
  7. 详解mysql查询缓存简单使用
  8. gorm操作MySql数据库的方法
  9. MySQL5.7 集群配置的步骤
  10. MySQL 普通索引和唯一索引的区别详解