Pure Java Environment Get APK information (package name, version, version number, size, permissions ...), Java language writing PC-side get apk information

Source: Internet
Author: User
Tags addgroup java se

Pure Java Environment get APK information: Package name, version, version number, size, permissions ...

Pure Java Environment Get APK information requires two packages:Axmlprinter2.jar and Jdom.jar, used to decompile XML and parse XML

Project directory



This class is the one that gets the APK information

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 ();D ocument Document = null;try{document = Builder.build (Getxmlinputstream (Apkpath)) ;} catch (Exception e) {e.printstacktrace ();} Element root = Document.getrootelement ();//Node-->manifestapkinfo.setversioncode (Root.getattributevalue (" Versioncode ", NS)); Apkinfo.setversionname (Root.getattributevalue (" Versionname ", NS)); Apkinfo.setapkpackage ( Root.getattributevalue ("package", NS)); Element elemusesdk = Root.getchild ("USES-SDK");//child node-->uses-sdkapkinfo.setminsdkversion ( Elemusesdk.getattributevalue ("Minsdkversion", NS)); List listpermission = Root.getchildren ("uses-permission");//child node is a collection 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 version number:" +versioncode+ "\ nthe version name:" +versionname+ "\ n Package Name:" +packagename "); String str = "\ n version number:" \ +versioncode+ "\ n version name:" +versionname+ "\ n Package Name:" +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;}}

Directly on the code, next time to mend the explanation.

The following is a main class of interface, mainly read the APK location and size

/** * * @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 was called from within the constructor to initialize the form. * Warning:do not modify this code.     The content of this method was always * regenerated by the Form Editor. */@SuppressWarnings ("unchecked")//<editor-fold defaultstate= "collapsed" desc= "Generated Code" >//gen-begin:i        nitcomponents 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 ("Select File location");        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 ("Arial", 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). Ad DGroup (Layout.createsequentialgroup (). Addcontainergap (). AddGroup (Layout.createparallelgrou P (Javax.swing.GroupLayout.Alignment.LEADING). AddComponent (JScrollPane1, Javax.swing.GroupLayout.DEFAUL T_size, 542, Short.max_value). AddGroup (Layout.createsequentialgroup (). Addcompo         Nent (JButton1). Addgap (0, 0, short.max_value)))       . Addcontainergap ())); Layout.setverticalgroup (Layout.createparallelgroup (Javax.swing.GroupLayout.Alignment.LEADING). ADDG                Roup (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 ();                Note that the important sentence here is System.out.println (Fsv.gethomedirectory ());     Get Desktop Path   Filechooser.setcurrentdirectory (Fsv.gethomedirectory ());        Filechooser.setdialogtitle ("Select File path");        Filechooser.setapprovebuttontext ("OK");        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 name:" + file.getname () + "\ n" + "size:" + getfilesize (file) + "Bit;" + (float) getfilesize (file)/(float) 1024/(float) 1024+ "MB "+apkutil.getapkinfo (File.getpath ()) +" \ 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 (). E Ndswith (". apk")) {Pathlist.add (File.getpath ());} Else{file filelist[] = File.listfiles (); for (File f:filelist) {try {getList (f);} catch (Exception e) {//TODO Auto-generat    Ed catch Blocke.printstacktrace ();}}} /** * Gets the specified file size * @param f * @return * @throws Exception */Private long getfilesize (file F        Ile) 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 FE El *///<editor-fold defaultstate= "collapsed" desc= "look and feel setting code (optional)" >/* If Ni         MBus (introduced in Java SE 6) isn't 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.G        Etname ()). 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.uti        L.logging.level.severe, NULL, ex); } catch (Javax.swing.UnsupportedLookAndFeelException ex) {Java.util.logging.Logger.getLogger (MainTest.class.ge        Tname ()). log (Java.util.logging.Level.SEVERE, NULL, ex); }//</editor-fold>/* Create and display the form */java.awt.EventQueue.invokeLater (new Runnab            Le () {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}

Example test, which was found in Jinshan


Here only check the package name, version, version number, size, no check permissions, permissions are I blocked off

List listpermission = Root.getchildren ("uses-permission");//child node is a collection list permissions = new ArrayList (); for (Object object:listpermission) {String permission = ((Element) object). Getattributevalue ("name", NS);p Ermissions.add ( permission);} Apkinfo.setuses_permission (permissions);
This section is the code that gets the permission

SOURCE download

Respect the original, reproduced please specify the source:http://blog.csdn.net/chillax_li/article/details/41850863



Pure Java Environment Get APK information (package name, version, version number, size, permissions ...), Java language writing PC-side get apk information

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.