美文网首页android系统应用开发
读取到手机插入SD卡事件,静默安装指定目录下的APK

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

作者: Ayugone | 来源:发表于2019-01-10 10:44 被阅读0次

    由于测试硬件需要安装好几个不同的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过滤广播,在执行相应的静默安装代码就好了。

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/cryorqtx.html