純JAVA環境擷取APK資訊(包名,版本,版本號碼,大小,許可權...),純JAVA語言編寫PC端擷取APK資訊,apk包名

來源:互聯網
上載者:User

純JAVA環境擷取APK資訊(包名,版本,版本號碼,大小,許可權...),純JAVA語言編寫PC端擷取APK資訊,apk包名

純JAVA環境擷取APK資訊:包名,版本,版本號碼,大小,許可權...

純Java環境擷取APK資訊需要兩個包:AXMLPrinter2.jar 跟jdom.jar,用於反編譯XML和解析XML的

項目目錄



這個類是擷取APK資訊的

public class ApkUtil {private static final Namespace NS = Namespace.getNamespace("http://schemas.android.com/apk/res/android");@SuppressWarnings("unchecked")public static String getApkInfo(String apkPath){ApkInfo apkInfo = new ApkInfo();SAXBuilder builder = new SAXBuilder();Document document = null;try{document = builder.build(getXmlInputStream(apkPath));}catch (Exception e) {e.printStackTrace();}Element root = document.getRootElement();//跟節點-->manifestapkInfo.setVersionCode(root.getAttributeValue("versionCode",NS));apkInfo.setVersionName(root.getAttributeValue("versionName", NS));apkInfo.setApkPackage(root.getAttributeValue("package", NS));Element elemUseSdk = root.getChild("uses-sdk");//子節點-->uses-sdkapkInfo.setMinSdkVersion(elemUseSdk.getAttributeValue("minSdkVersion", NS));List listPermission = root.getChildren("uses-permission");//子節點是個集合List permissions = new ArrayList();for(Object object : listPermission){String permission = ((Element)object).getAttributeValue("name", NS);permissions.add(permission);}apkInfo.setUses_permission(permissions);String s = root.getAttributes().toString();String c[] = s.split(",");String versionCode = null;String versionName = null;String packageName = null;for(String a: c){if(a.contains("versionCode")){versionCode = a.substring(a.indexOf("versionCode=\"")+13, a.lastIndexOf("\""));}if(a.contains("versionName")){versionName = a.substring(a.indexOf("versionName=\"")+13, a.lastIndexOf("\""));}if(a.contains("package")){packageName = a.substring(a.indexOf("package=\"")+9, a.lastIndexOf("\""));}}System.out.println("\n版本號碼:"+versionCode+"\n版本名:"+versionName+"\n包名:"+packageName);String str = "\n版本號碼:"+versionCode+"\n版本名:"+versionName+"\n包名:"+packageName;//return root.getAttributes().toString();return str;}private static InputStream getXmlInputStream(String apkPath) {InputStream inputStream = null;InputStream xmlInputStream = null;ZipFile zipFile = null;try {zipFile = new ZipFile(apkPath);ZipEntry zipEntry = new ZipEntry("AndroidManifest.xml");inputStream = zipFile.getInputStream(zipEntry);AXMLPrinter xmlPrinter = new AXMLPrinter();xmlPrinter.startPrinf(inputStream);xmlInputStream = new ByteArrayInputStream(xmlPrinter.getBuf().toString().getBytes("UTF-8"));} catch (IOException e) {e.printStackTrace();try {inputStream.close();zipFile.close();} catch (IOException e1) {e1.printStackTrace();}}return xmlInputStream;}}

直接上代碼,下次再補過講解.

下面這個是一個介面的主類,主要讀取APK位置和大小

/** * * @author Administrator */public class MainTest extends javax.swing.JFrame {    private File f = null;    private List<String> pathList = new ArrayList<String>();;        /**     * Creates new form NewJFrame     */    public MainTest() {        initComponents();    }    /**     * This method is called from within the constructor to initialize the form.     * WARNING: Do NOT modify this code. The content of this method is always     * regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents    private void initComponents() {        jButton1 = new javax.swing.JButton();        jScrollPane1 = new javax.swing.JScrollPane();        jTextArea1 = new javax.swing.JTextArea();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        jButton1.setText("選擇檔案位置");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                openFilePath(evt);            }        });        jTextArea1.setColumns(20);        jTextArea1.setFont(new java.awt.Font("宋體", 0, 20));        jTextArea1.setRows(5);        jScrollPane1.setViewportView(jTextArea1);        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addContainerGap()                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)                    .addGroup(layout.createSequentialGroup()                        .addComponent(jButton1)                        .addGap(0, 0, Short.MAX_VALUE)))                .addContainerGap())        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(layout.createSequentialGroup()                .addContainerGap()                .addComponent(jButton1)                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)                .addContainerGap())        );        pack();    }// </editor-fold>//GEN-END:initComponents    private void openFilePath(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFilePath        // TODO add your handling code here:        int result = 0;        String path = null;        JFileChooser fileChooser = new JFileChooser();        FileSystemView fsv = FileSystemView.getFileSystemView();  //注意了,這裡重要的一句        System.out.println(fsv.getHomeDirectory());                //得到案頭路徑        fileChooser.setCurrentDirectory(fsv.getHomeDirectory());        fileChooser.setDialogTitle("選擇檔案路徑");        fileChooser.setApproveButtonText("確定");        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);        result = fileChooser.showOpenDialog(this);        if (JFileChooser.APPROVE_OPTION == result) {            path = fileChooser.getSelectedFile().getPath();            System.out.println("path: " + path);        }        if(path==null || path.equals("")){            return;        }        jTextArea1.setText("");        f = new File(path);        if (f.exists()) {        getList(f);                    for (String filePath: pathList) {            File file = new File(filePath);            if (!file.exists()) {            break;            }                try {                    String str = jTextArea1.getText();                    String s = "檔案名稱:" + file.getName() + "\n" + "檔案大小:"+ getFileSize(file) + "Bit; "+ (float)getFileSize(file)/(float)1024/(float)1024+"MB"                     +ApkUtil.getApkInfo(file.getPath()) + "\n\n";                    jTextArea1.setText(s + str);                } catch (Exception ex) {                    Logger.getLogger(MainTest.class.getName()).log(Level.SEVERE, null, ex);                }            }        }    }    private void getList(File file){    if(file.isFile() && file.getName().endsWith(".apk")){pathList.add(file.getPath());}else{File fileList[] = file.listFiles();for(File f : fileList){try {getList(f);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}    }        /**     * 擷取指定檔案大小     * @param f     * @return     * @throws Exception     */    private long getFileSize(File file) throws Exception {        long size = 0;        if (file.exists()) {            FileInputStream fis = null;            fis = new FileInputStream(file);            size = fis.available();        } else {            file.createNewFile();        }        return size;    }    /**     * @param args the command line arguments     */    public static void main(String args[]) {        /* Set the Nimbus look and feel */        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html          */        try {            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {                if ("Nimbus".equals(info.getName())) {                    javax.swing.UIManager.setLookAndFeel(info.getClassName());                    break;                }            }        } catch (ClassNotFoundException ex) {            java.util.logging.Logger.getLogger(MainTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (InstantiationException ex) {            java.util.logging.Logger.getLogger(MainTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (IllegalAccessException ex) {            java.util.logging.Logger.getLogger(MainTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        } catch (javax.swing.UnsupportedLookAndFeelException ex) {            java.util.logging.Logger.getLogger(MainTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);        }        //</editor-fold>        /* Create and display the form */        java.awt.EventQueue.invokeLater(new Runnable() {            public void run() {                new MainTest().setVisible(true);            }        });    }    // Variables declaration - do not modify//GEN-BEGIN:variables    private javax.swing.JButton jButton1;    private javax.swing.JScrollPane jScrollPane1;    private javax.swing.JTextArea jTextArea1;    // End of variables declaration//GEN-END:variables}

執行個體測試,這是在金山找的


 

這裡只查了包名,版本,版本號碼,大小,沒有查許可權,許可權被我屏蔽掉了

List listPermission = root.getChildren("uses-permission");//子節點是個集合List permissions = new ArrayList();for(Object object : listPermission){String permission = ((Element)object).getAttributeValue("name", NS);permissions.add(permission);}apkInfo.setUses_permission(permissions);

這一段就是擷取許可權的代碼


有時候有些apk資訊讀不出,只要將下面這些代碼注釋掉就行了

apkInfo.setVersionCode(root.getAttributeValue("versionCode",NS));apkInfo.setVersionName(root.getAttributeValue("versionName", NS));apkInfo.setApkPackage(root.getAttributeValue("package", NS));Element elemUseSdk = root.getChild("uses-sdk");//子節點-->uses-sdkapkInfo.setMinSdkVersion(elemUseSdk.getAttributeValue("minSdkVersion", NS));List listPermission = root.getChildren("uses-permission");//子節點是個集合List permissions = new ArrayList();for(Object object : listPermission){String permission = ((Element)object).getAttributeValue("name", NS);permissions.add(permission);}apkInfo.setUses_permission(permissions);

源碼下載

尊重原創,轉載請註明出處:http://blog.csdn.net/chillax_li/article/details/41850863



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.