读取到手机插入SD卡事件,静默安装指定目录下的APK

由于测试硬件需要安装好几个不同的apk来测试手机功能是否正常,但是机器数量一多,每次安装apk都很耗时,所以想把SD卡插入手机之后就直接静默安装这些APK

首先,静默安装是需要系统root的权限的,所以第三方应用是做不到静默安装的,所以我们从系统源码动手来实现

1,在Settings工程中弄一个接收SD卡插入的广播接收器

package com.android.settings;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.util.Log;

public class StrogeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    if ("android.intent.action.MEDIA_MOUNTED".equals(intent.getAction())) {
        String path = intent.getData().getPath();
        String filename = "";
        String suf = "";// 文件后缀
        String apkPath = takePicRootDir(context);
        if (apkPath != null) {

            File file = new File(apkPath);
            if (file.exists() && file.isDirectory()) {
                File[] files = file.listFiles();// 文件夹下的所有文件或文件夹
                for (int i = 0; i < files.length; i++) {

                    if (files[i].isDirectory()) {
                        Log.e("hahaha","files[i].isDirectory()"+files[i].isDirectory());
                    } else {
                        filename = files[i].getName();
                        int j = filename.lastIndexOf(".");
                        suf = filename.substring(j + 1);// 得到文件后缀
                        
                        if (suf.equalsIgnoreCase("apk"))// 判断是不是apk后缀的文件
                        {
                             String strFileName =
                             files[i].getAbsolutePath();
                             installSilent(strFileName);
                        }
                    }

                }
            }
        }
    }

}

/**
 * 判断当前存储卡是否可用
 **/
public boolean checkSDCardAvailable() {
    return Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED);
}

/**
 * 获取当前需要查询的文件夹路径
 **/
public String takePicRootDir(Context context) {
    if (checkSDCardAvailable()) {
        return getStoragePath(context,true) + File.separator
                + "JB_AUTO_INSTALL";
    }
    return null;
}
  //静默安装代码,filePath为apk的全路径
public static int installSilent(String filePath) {  
    File file = new File(filePath);  
    if (filePath == null || filePath.length() == 0 || file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {  
        return 1;  
    }  
  
    String[] args = { "pm", "install", "-r", filePath };  
    ProcessBuilder processBuilder = new ProcessBuilder(args);  
    Process process = null;  
    BufferedReader successResult = null;  
    BufferedReader errorResult = null;  
    StringBuilder successMsg = new StringBuilder();  
    StringBuilder errorMsg = new StringBuilder();  
    int result;  
    try {  
        process = processBuilder.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 (IOException e) {  
        e.printStackTrace();  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            if (successResult != null) {  
                successResult.close();  
            }  
            if (errorResult != null) {  
                errorResult.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        if (process != null) {  
            process.destroy();  
        }  
    }  
  
    // TODO should add memory is not enough here  
    if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {  
        result = 0;  
    } else {  
        result = 2;  
    }  
    Log.d("test-test", "successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);  
    return result;  
}  //获取外置SD卡的路径,is_removale为true时则为获取外置SD卡路径,false为内置SD卡路径
private static String getStoragePath(Context mContext, boolean is_removale) {  

      StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
}

}

在Settings工程的AndroidManifest.xml声明该广播


1547086819(1).png

记得要加<data android:scheme="file"/>才可以收到SD卡的插拔事件广播
具体原因可以参考以下链接
https://blog.csdn.net/silenceburn/article/details/6083375

由于Settings工程本身没有安装apk的权限声明,所以要在Settings工程的AndroidManifest.xml声明该权限
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

这样在就可以在插入外置SD卡后,重启手机之后,就会收到SD卡已插入事件,再进行静默安装。

但是在这里有个问题,就是安装了之后,会有"安装成功,是否删除安装包?"的提示框出现,显然这个不是静默安装的标准,所以要去掉他。
在Settings里面使用grep -rn “安装成功” ./ 命令就可以搜索到Settings工程下的 DeleteAPKResource.java文件 ,这个Activity就是弹出"安装成功,是否删除安装包?"的提示框的Activity。
package com.android.settings;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.UserHandle;
import android.provider.MediaStore;
import android.provider.MediaStore.Files.FileColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews.OnClickHandler;
import android.widget.TextView;
import android.widget.Toast;

public class DeleteAPKResource extends Activity {
public static final String TAG = "DeleteAPKResource";

String path;
File file;
Button btn_cancel;
Button btn_delete;
TextView tv_content;
TextView tv_title;
DialogInterface.OnClickListener dialogOnClickListener;
PackageManager pm;
ApplicationInfo appinfo;
String packageName;
AlertDialog dialog;
boolean showNotificationFlag = true; //[BUGFIX]-Add by SCDTABLET.(mengqin.zhang@tcl.com),14/09/2016,defect 2828222

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    // this.setContentView(R.layout.package_monitor_dialog);
    // this.setTitle(title);

    Intent mintent = getIntent();
    path = mintent.getStringExtra("RESOURCE_FILE_PACH");
    packageName = mintent.getStringExtra("PACKAGE_NAME");

    init();

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    showMyDialog();
}

private void showMyDialog() {
    // TODO Auto-generated method stub
    if (dialog != null) {
        dialog.show();
    }
}

private void CancleNotification() {
    // TODO Auto-generated method stub
    NotificationManager mNotificationMgr =
            (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
    mNotificationMgr.cancelAsUser(null, getNotificationIdWithPackagesName(appinfo.packageName), UserHandle.ALL);
    //mNotificationMgr.cancelAll();
}

private void SendNotification() {
    // TODO Auto-generated method stub
    Intent mIntent = getIntent();

    NotificationManager mNotificationMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = getNotificationIdWithPackagesName(appinfo.packageName);
    //[BUGFIX]-Mod-BEGIN by SCDTABLET.(mengqin.zhang@tcl.com),31/08/2016,defect 2824520
    CharSequence title = getResources().getString(R.string.delete_apk_title);//"Delete APK Resource";
    CharSequence details = getResources().getString(R.string.delete_apk_detail);//"This application has been installed, you can delete the APK source files!";
    //[BUGFIX]-Mod-END by SCDTABLET.(mengqin.zhang@tcl.com),31/08/2016,defect 2824520
    // title = this.getText(R.string.move_data_notification_title);
    // details = this.getText(R.string.move_data_notification_details);
    PendingIntent intent = PendingIntent.getActivityAsUser(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT,
            null, UserHandle.CURRENT);
    Notification notification = new Notification.Builder(this)
            .setLargeIcon(drawableToBitamp(appinfo.loadIcon(pm)))
            .setSmallIcon(R.drawable.ic_delete_apk_48dp)
            .setTicker(title)
            .setColor(this.getColor(com.android.internal.R.color.system_notification_accent_color))
            .setContentTitle(title)
            .setContentText(details)
            .setContentIntent(intent)
            .setStyle(new Notification.BigTextStyle().bigText(details))
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setCategory(Notification.CATEGORY_SYSTEM).build();
    mNotificationMgr.notifyAsUser(null, notificationId, notification, UserHandle.ALL);
}

@SuppressLint("InlinedApi")
private void init() {
    // TODO Auto-generated method stub
    file = new File(path);
    if (!file.exists()||path.contains("/storage/3530-3138/JB_AUTO_INSTALL")) {
        finish();
        Log.e(TAG, "Resource file is not exist!");
    }

    dialogOnClickListener = new DialogOnClickListener();

    pm = getPackageManager();
    try {
        appinfo = pm.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //[BUGFIX]-MOD-BEGIN by SCDTABLET.(teng-liu@tcl.com),09/09/2016,DEFECT2879349,<for monkey test>
    if (appinfo == null || pm == null) {
        Toast.makeText(this, "Get APP info error!", Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Get APP info error!");
        finish();
    }
    //[BUGFIX]-MOD-END by SCDTABLET.(teng-liu@tcl.com),09/09/2016,DEFECT2879349,<for monkey test>
    createDialog();
    dialog.setOnDismissListener(new DialogOnDismissListener());
}

private void createDialog() {
    // TODO Auto-generated method stub
    StringBuilder messageBuilder = new StringBuilder();
    //messageBuilder.append("Your APP: ");
    //messageBuilder.append(appinfo.loadLabel(pm));
    //[BUGFIX]-Mod-BEGIN by SCDTABLET.(mengqin.zhang@tcl.com),31/08/2016,defect 2824520
    messageBuilder.append(getResources().getString(R.string.delete_apk_detail, appinfo.loadLabel(pm)));
    //[BUGFIX]-Mod-END by SCDTABLET.(mengqin.zhang@tcl.com),31/08/2016,defect 2824520
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle(android.R.string.dialog_alert_title);
    dialogBuilder.setIcon(appinfo.loadIcon(pm));
    dialogBuilder.setPositiveButton(R.string.delete_apk_dilog_ok_btn, dialogOnClickListener);
    dialogBuilder.setNegativeButton(android.R.string.cancel, dialogOnClickListener);
    dialogBuilder.setMessage(messageBuilder.toString());
    dialog = dialogBuilder.create();
}

public void deleteSourceFile() {
    // TODO Auto-generated method stub
    boolean delete = file.delete();
    if (delete) {
        //[BUGFIX]-Mod-BEGIN by SCDTABLET.(mengqin.zhang@tcl.com),10/18/2016,task 3103567
        Toast.makeText(this, getResources().getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, getResources().getString(R.string.delete_fail) +" "+ path, Toast.LENGTH_LONG).show();
        //[BUGFIX]-Mod-BEGIN by SCDTABLET.(mengqin.zhang@tcl.com),10/18/2016,task 3103567
    }

    List<String> list = new ArrayList<String>();
    list.add(path);
    deleteFileInMediaStore(list);//update MediaStore

    System.gc();
}

@SuppressLint("InlinedApi")
public void deleteFileInMediaStore(List<String> paths) {
    //new FavoriteManager(mContext).deleteFavoriteFile(paths);
    Uri uri = MediaStore.Files.getContentUri("external");
    int max = 300;
    for (int i = 0; paths != null && i < Math.ceil(1.0f * paths.size() / max); i++) {
        StringBuilder where = new StringBuilder();
        where.append(FileColumns.DATA);
        where.append(" IN(");
        int index = i * max;
        int length = Math.min((i + 1) * max, paths.size());
        List<String> fileList = new ArrayList<String>();
        for (int j = index; j < length; j++) {
            fileList.add(paths.get(j));
            where.append("?");
            if (j < length - 1) {
                where.append(",");
            }
        }
        where.append(")");
        String[] whereArgs = new String[length - index];
        fileList.toArray(whereArgs);
        try {
            getContentResolver().delete(uri, where.toString(), whereArgs);
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

public Bitmap drawableToBitamp(Drawable drawable) {
    Bitmap bitmap;
    int w = drawable.getIntrinsicWidth();
    int h = drawable.getIntrinsicHeight();
    Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
            : Bitmap.Config.RGB_565;
    bitmap = Bitmap.createBitmap(w, h, config);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, w, h);
    drawable.draw(canvas);
    return bitmap;
}

public int getNotificationIdWithPackagesName(String str) {
    int ID = 0;
    if(str == null){
        return 0;
    }
    for(int i = 0; i < str.length(); i++){
       ID = ID + (i * str.charAt(i) + i + str.charAt(i));
    }
    return ID;
}

class DialogOnClickListener implements DialogInterface.OnClickListener {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        if (which == Dialog.BUTTON_POSITIVE) {
            deleteSourceFile();
            CancleNotification();
        } else {
            SendNotification();
            finish();
        }
        showNotificationFlag = false;  //[BUGFIX]-Add by SCDTABLET.(mengqin.zhang@tcl.com),14/09/2016,defect 2828222
    }
}

class DialogOnDismissListener implements DialogInterface.OnDismissListener {

    @Override
    public void onDismiss(DialogInterface dialog) {
        // TODO Auto-generated method stub
        //[BUGFIX]-Mod-BEGIN by SCDTABLET.(mengqin.zhang@tcl.com),14/09/2016,defect 2828222
        if (showNotificationFlag == true) {
            SendNotification();
        }
        //[BUGFIX]-Mod-END by SCDTABLET.(mengqin.zhang@tcl.com),14/09/2016,defect 2828222
        finish();
    }
}

}

我们可以在init中加入判断


image.png

如果是我们自己目录下的安装包,就直接关掉这个界面,不让它弹窗就可以了。

如果说为了让我们的系统能够支持第三方调用他们想静默安装的路径下的apk,加个action过滤广播,在执行相应的静默安装代码就好了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容