Android Context && Android common system services (currently running package name/current network status and switching network/audio services/Motor Services) (RPM)

Source: Internet
Author: User

Ext.: http://blog.csdn.net/zhandoushi1982/article/details/8501773

Context literal meaning, located in the Android.content.Context of the framework. In fact, the class is a long type, similar to the handle handle in Win32, many methods need to pass the context to get the caller's instance, such as toast the first parameter is the context, generally in the activity we use this instead , and to a button's OnClick (View view) method, we use this to error, we may use activityname.this to solve (or getbasecontext ()/ Getapplicationcontext ()).

The class that implements the context has several models specific to Android, Activity, service, and Broadcastreceiver. The context provides an interface for global information about the application environment while initiating application-level operations, such as starting activity,broadcasting and receiving intents. The number of context formulas common to the App app are: Total number of instances = number of Service + activity + 1 (application corresponding context instance).

Broadcastreceiver uses the context to be used by this formal parameter in the public void onreceive (context context, Intent Intent).

=============================================================================================================== =================

Use Android.app. Activity. Getsystemservice This method, you can get the common services of the system and some methods of the column. Examples are as follows:

(1) Get the app package name that is currently running

Create an activity, first in the XML to add permissions to get the system running tasks:

<uses-permission  

Otherwise, the runtime will report an exception: Java.lang.SecurityException:Permission denial: ... Requires Android.permission.GET_TASKS
The response core source code is as follows:

Import Android.app.activitymanager;public class Mainactivity extends Activity {    @Override public    void OnCreate (Bundle savedinstancestate) {    log.i ("Zhangcheng", "Run Here");        Super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        TextView StrText = (TextView) Findviewbyid (r.id.callinfo);        Activitymanager Activitymanager = (activitymanager) getsystemservice (Context.activity_service); Get page Management Service        String currentpackagename = "";        Currentpackagename = activitymanager.getrunningtasks (1)        . Get (0). Topactivity.getpackagename ();// Gets the package name of the top page of the current running task        strtext.settext (currentpackagename);}    }

My Java src path is: callphone\src\com\example\callphone\, so the package name that is finally displayed is: Com.example.callphone.

=========================================================================================
Sometimes it is necessary to determine whether the current app is networked, WiFi, or other network connection methods. The core code is as follows:

(1) Current network type, whether connected to the Internet

Connectivitymanager manager = (Connectivitymanager) getsystemservice (context.connectivity_service);  if (manager = = null) return;        Networkinfo activenetworkinfo = Manager.getactivenetworkinfo ();          if (Activenetworkinfo = = null)        return;        TextView display = (TextView) Findviewbyid (r.id.testview1);                if ((activenetworkinfo.gettype () = = Connectivitymanager.type_wifi)        && activenetworkinfo.isconnected ()) {        Display.settext ("WIFI NET");                                   } else if (activenetworkinfo.gettype () = = Connectivitymanager.type_mobile        && Activenetworkinfo.isconnected ()) {          Display.settext ("MOBILE NET");        }

The permissions Required

(2) Switch WiFi:

Permissions that are used

Switch button

Wifimanager Wifimanager;wifimanager = (wifimanager) getsystemservice (context.wifi_service);p ublic void OnClick (View V {    if (wifimanager.iswifienabled ()) {    wifimanager.setwifienabled (false);    } else{    wifimanager.setwifienabled (true);}    }

(3) Switch mobile network. This is more complicated because Connectivitymanager's setmobiledataenabled function is hidden, so it must be called by the Java function Reflection (Java reflection related content can be found in other people's posts http:// write.blog.csdn.net/postedit/8501773, currently used but not understood).

Defining Global Variables

Context context = this; Connectivitymanager Manager; TextView display;

The OnCreate function of the page is initialized

Manager = (Connectivitymanager) getsystemservice (context.connectivity_service);  if (manager = = null) Return;display = (TextView) Findviewbyid (r.id.testview1);   Prompt for current mobile network status

Reflection function

public boolean InvokeMethod (String methodname,object[]  Arg) throws Exception {Class Ownerclass = Manager.getclass () ;        class[]  argsclass = null;        if (arg! = null) {            Argsclass = new Class[1];            Argsclass[0] = Arg.getclass ();        }        method = Ownerclass.getmethod (MethodName, argsclass);                Boolean IsOpen = (Boolean) Method.invoke (Manager, ARG);        return isOpen;} Public Object Invokebooleanargmethod (String Methodname,boolean value) throws Exception {        Class ownerclass = Manager . GetClass ();        class[]  argsclass = new Class[1];        Argsclass[0] = Boolean.class;        method = Ownerclass.getmethod (Methodname,argsclass);        Return Method.invoke (manager, value);}

Repeatedly click a button, you can see the mobile network on the switch, from the status bar icon can be seen from the page TextView text can also be seen corresponding.

public void OnClick (View v) {//log.i ("Zhangcheng", "click"); object[] arg = null;  try {  Boolean ismobiledataenable = InvokeMethod ("getmobiledataenabled", Arg);  if (!ismobiledataenable) {  Invokebooleanargmethod ("setmobiledataenabled", true);  Display.settext ("MOBILE NET on");  }  else{  Invokebooleanargmethod ("setmobiledataenabled", false);  Display.settext ("MOBILE NET OFF");  }  } catch (Exception e) {   //TODO auto-generated catch block  e.printstacktrace ();}  }

The permissions Required

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name= "Android.permission.CHANGE_NETWORK_STATE"/>

============================================================================================

Get the ringtone and volume of your Android phone through the program. Also, the way to set the ringtone and volume is simple!

Audiomanager Maudiomanager = (audiomanager) getsystemservice (Context.audio_service);
(1) Call volume

int max = Maudiomanager.getstreammaxvolume (Audiomanager.stream_voice_call); int current = Maudiomanager.getstreamvolume (Audiomanager.stream_voice_call); LOG.D ("Vioce_call", "Max:" + Max + "Current:" + current);

(2) System volume

(3) Ringtone volume

(4) Music volume

(5) Prompt sound volume

max = Maudiomanager.getstreammaxvolume (audiomanager.stream_alarm); Current = Maudiomanager.getstreamvolume (Audiomanager.stream_alarm); LOG.D ("ALARM", "Max:" + Max + "Current:" + current);

The way to set the volume is also simple: public void setstreamvolume (int streamtype, int index, int flags), where Streamtype is the ringtone type, For example: Audiomanager.stream_voice_call, Audiomanager.stream_system, etc., index is the volume size, Falgs is the flag bit.

Here's how to modify the audio settings:

(6) Mute when calling

System.out.println ("Ismicrophonemute =" + Audiomanager.ismicrophonemute ()); Audiomanager.setmicrophonemute (! Audiomanager.ismicrophonemute ());

(7) Set up speakerphone when calling

System.out.println ("Isspeakerphoneon =" + Audiomanager.isspeakerphoneon ()); Audiomanager.setspeakerphoneon (! Audiomanager.isspeakerphoneon ());

Don't forget to modify the permissions <uses-permission android:name= "Android.permission.MODIFY_AUDIO_SETTINGS"/>
===========================================================================================
To set the vibration:

Mvibrator = (Vibrator) mcontext.getsystemservice (service.vibrator_service);   Long[] Pattern = {150, 100};  off/on/off/on ... Mvibrator.vibrate (Pattern,-1);

Reference Original: http://www.cnblogs.com/wgw8299/articles/2128202.html

Reference Original: http://blog.csdn.net/comkingfly/article/details/7359950

Reference Original: http://blog.csdn.net/ponderforever/article/details/7167591

Reference Original: http://blog.csdn.net/gf771115/article/details/6996577


Android Context && Android common system services (currently running package name/current network status and switching network/audio services/Motor Services) (RPM)

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.