Android: Using Java reflection to invoke @hide Api__java

Source: Internet
Author: User
Tags modifier reflection

Set up to use 3G data features:

To see the Hidden API (Connectivitymanager.java) from source code:

/**
     * Sets The persisted value for enabling/disabling Mobile data.
     *
     @param enabled Whether the mobile data connection should is
     *            used or not.
     * @hide/public
    void Setmobiledataenabled (Boolean enabled) {
        try {
            mservice.setmobiledataenabled ( enabled);
        } catch (RemoteException e) {
        }
    }

This functionality is implemented through the Java Reflection feature, which calls
mservice.setmobiledataenabled (enabled);

The code is as follows:

private void Enablemobiledata (Boolean enable) {Connectivitymanager Connectivitymanager = (connectivitymanager) getsyst

		Emservice (Context.connectivity_service);
			try {//Get mservice//Android.net.ConnectivityManager.mService;
			Field field = Class.forName (ConnectivityManager.class.getName ()). Getdeclaredfield ("Mservice");
			Field.setaccessible (TRUE);
			///permission modifier int mo = Field.getmodifiers ();
			String priv = modifier.tostring (MO);
			Property type Class<?> type = Field.gettype ();
            LOG.I (TAG, Priv + "" + type.getname () + "" + field.getname () + ";"); //Get object ' Mservice Object obj = Field.get (Connectivitymanager);//Connectivitymanager.mservice/Get I
			Connectivitymanager class Class MyClass = Class.forName (Obj.getclass (). GetName ()); LOG.I (TAG, "CLASS3:" + obj.getclass (). GetName ());//Iconnectivitymanager/Get Android.net.IConnectivityManager// public void Setmobiledataenabled (Boolean enabled) throws
			Android.os.RemoteException;

			Method method = Myclass.getdeclaredmethod ("setmobiledataenabled", Boolean.class);
			/* String pstr = "";
			class<?>[] Parameters = Method.getparametertypes ();
			int count = Parameters.length;
			LOG.I (TAG, "Count:" + count);
				if (Count > 0) {for (class<?> p:parameters) {pstr + = P.getname () + ",";
				} pstr = pstr.substring (0, Pstr.length ()-1);
			LOG.I (TAG, "pstr:" + pstr); LOG.I (TAG, Modifier.tostring (Method.getmodifiers ()) + "" + Method.getreturntype (). GetName () + "" + METHOD.GETN
			Ame () + "(" + Pstr +); ");
			*/Method.setaccessible (TRUE);

		Method.invoke (obj, enable);
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }

	}

Note Add the appropriate permission:

   <uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android: Name= "Android.permission.INTERNET"/>
    <uses-permission android:name= "Android.permission.CHANGE_NETWORK" _state "/>


Add a code that uses Java reflection to parse APK package information on the Web:

ref:http://blog.csdn.net/sodino/article/details/6215224//using the reflection mechanism to invoke the Android @hide API to resolve public static void 
		Extractapkinfoext (string apkpath, Downloadtask Task) {string path_packageparser = "Android.content.pm.PackageParser";
		String Path_assetmanager = "Android.content.res.AssetManager"; try {//APK package file path//This is a package interpreter, is hidden//constructor parameter only one, APK file path//Packageparser Packageparser = new Pa
			Ckageparser (Apkpath);
			Class pkgparsercls = Class.forName (Path_packageparser);
			class[] Typeargs = new Class[1];
			Typeargs[0] = String.class;
			Constructor pkgparserct = Pkgparsercls.getconstructor (Typeargs);
			object[] Valueargs = new Object[1];
			Valueargs[0] = Apkpath;
			Object Pkgparser = pkgparserct.newinstance (Valueargs);
			if (Constants.debug_mode) log.d (TAG, "Pkgparser:" + pkgparser.tostring ());
			This is related to the display, which involves some pixel display and so on, we use the default situation displaymetrics metrics = new Displaymetrics ();
			Metrics.settodefaults (); Packageparser.package Mpkginfo = packageparser.parsepackage (new//File (Apkpath), Apkpath,//metrics, 0);
			Typeargs = new Class[4];
			Typeargs[0] = File.class;
			TYPEARGS[1] = String.class;
			TYPEARGS[2] = Displaymetrics.class;
			TYPEARGS[3] = Integer.type;
			Method PKGPARSER_PARSEPACKAGEMTD = Pkgparsercls.getdeclaredmethod ("Parsepackage", Typeargs);
			Valueargs = new Object[4];
			Valueargs[0] = new File (Apkpath);
			VALUEARGS[1] = Apkpath;
			VALUEARGS[2] = metrics;
			VALUEARGS[3] = 0;
			Object pkgparserpkg = Pkgparser_parsepackagemtd.invoke (Pkgparser, Valueargs);
			if (pkgparserpkg = = null) {return;
			}//Application information packet, this public, but some functions, variables not public//applicationinfo info = mpkginfo.applicationinfo;
			Field appinfofld = Pkgparserpkg.getclass (). Getdeclaredfield ("ApplicationInfo");

			ApplicationInfo info = (applicationinfo) appinfofld. Get (PKGPARSERPKG);
			Get versioncode Field versioncodefld = Pkgparserpkg.getclass (). Getdeclaredfield ("Mversioncode");int versioncode = ((Integer) Versioncodefld.get (pkgparserpkg)). Intvalue ();

			Get versionname Field versionnamefld = Pkgparserpkg.getclass (). Getdeclaredfield ("Mversionname");

			String versionname = (string) versionnamefld.get (pkgparserpkg);
			The UID output is "-1" because it is not installed and the system does not assign its UID.
			if (Constants.debug_mode) log.d (TAG, "pkg:" + info.packagename + "uid=" + info.uid);
			Resources PRes = Getresources ();
			Assetmanager assmgr = new Assetmanager ();
			Assmgr.addassetpath (Apkpath);

			Resources res = new assmgr, Pres.getdisplaymetrics (),//Pres.getconfiguration ());
			Class assetmagcls = Class.forName (Path_assetmanager);
			Constructor ASSETMAGCT = Assetmagcls.getconstructor ((class[)) null);
			Object Assetmag = assetmagct.newinstance ((object[)) null);
			Typeargs = new Class[1];
			Typeargs[0] = String.class;
			Method ASSETMAG_ADDASSETPATHMTD = Assetmagcls.getdeclaredmethod ("Addassetpath", Typeargs);
		Valueargs = new Object[1];	Valueargs[0] = Apkpath;
			Assetmag_addassetpathmtd.invoke (Assetmag, Valueargs);
			Resources res = mcontext.getresources ();
			Typeargs = new Class[3];
			Typeargs[0] = Assetmag.getclass ();
			TYPEARGS[1] = Res.getdisplaymetrics (). GetClass ();
			TYPEARGS[2] = Res.getconfiguration (). GetClass ();
			Constructor RESCT = Resources.class.getConstructor (Typeargs);
			Valueargs = new Object[3];
			Valueargs[0] = Assetmag;
			VALUEARGS[1] = Res.getdisplaymetrics ();
			VALUEARGS[2] = res.getconfiguration ();
			res = (resources) resct.newinstance (Valueargs);
			Charsequence label = NULL;
				if (info.labelres!= 0) {label = Res.gettext (Info.labelres);
				if (label = = NULL) {//label = (Info.nonlocalizedlabel!= null)?
				Info.nonlocalizedlabel//: Info.packagename;
			} task.settitle (string.valueof (label));
			if (Constants.debug_mode) log.d (TAG, "label=" + label); Here is the icon to read a apk program if (Info.icon!= 0) {drawable icon = res.getdrawable (Info.icon);
				Task.seticon ((bitmapdrawable) icon). Getbitmap ());
				ImageView image = (ImageView) Findviewbyid (R.id.appicon);
				Image.setvisibility (view.visible);
			Image.setimagedrawable (icon);
			} if (Versionname!= null) {task.setversionname (versionname);
			} task.setversioncode (Versioncode);
			Task.setpackagename (Info.packagename);
			if (Info.processname = = null) {info.processname = Info.packagename;
		} task.setprocessname (Info.processname);
		catch (Exception e) {e.printstacktrace ();
 }
	}


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.