Android的Context && 安卓常用系统服务(当前运行包名/当前网络状态和开关网络/音频服务)

        Context字面意思上下文,位于framework 的android.content.Context中。其实该类为LONG型,类似Win32中的Handle句柄,很多方法需要通过Context才能得到调用者的实例,比如说Toast的第一个参数就是Context,一般在Activity中我们直接用this代替;而到了一个button的onClick(View view)等方法时,我们用this时就会报错,我们可能使用ActivityName.this来解决(或者getBaseContext()/getApplicationContext())。

        实现Context的类主要有Android特有的几个模型,Activity、Service以及BroadcastReceiver。Context提供了关于应用环境全局信息的接口,同时启动应用级的操作,如启动Activity,broadcasting和接收intents。应用程序App共有的Context数目公式为: 总Context实例个数 = Service个数 + Activity个数 + 1(Application对应的Context实例)。

        BroadcastReceiver使用Context是通过在public void onReceive(Context context, Intent intent)这个形参来使用的。

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

          利用android.app.Activity.getSystemService这个方法,可以获得系统常用的服务及一些列方法。举例如下:

(1) 获得当前正在运行的应用包名

        创建一个activity,首先在XML中要添加获取系统运行任务的权限:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <uses-permission  android:name="android.permission.GET_TASKS" />  

否则运行时会报异常:java.lang.SecurityException: Permission Denial:。。。。。。requires android.permission.GET_TASKS
        响应核心源码如下:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. import android.app.ActivityManager;  
  2.   
  3. public class MainActivity extends Activity {  
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState) {  
  6.         Log.i("zhangcheng","run here");  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.         TextView strText = (TextView)findViewById(R.id.callinfo);  
  10.   
  11.         ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); //获得页面管理服务  
  12.         String currentPackageName = "";  
  13.   
  14.             currentPackageName = activityManager.getRunningTasks(1)  
  15.                     .get(0).topActivity.getPackageName();   //获得当前运行任务顶层页面的包名  
  16.             strText.setText(currentPackageName);  
  17.     }  
  18. }  

我的java src路径是:CallPhone\src\com\example\callphone\,所以最终显示的包名是:com.example.callphone。

=========================================================================================
       有时需要判断当前app是否联网,是用的WIFI还是其他网络连接方式等。核心代码如下:

(1)当前联网网络类型,是否联网了

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);    
  2. if(manager == null)  
  3.     return;  
  4.       NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();    
  5.       if(activeNetworkInfo == null)  
  6.         return;  
  7.       TextView display = (TextView)findViewById(R.id.testview1);  
  8.         
  9.       if((activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)  
  10.             && activeNetworkInfo.isConnected()){  
  11.         display.setText("WIFI NET");                             
  12.       }else if(activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE  
  13.             && activeNetworkInfo.isConnected()){    
  14.         display.setText("MOBILE NET");  
  15.       }  

需要的权限

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />   

 

(2)开关WIFI:

用到的权限

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />   
  2. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />   

开关按钮

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. WifiManager wifiManager;  
  2. wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);  
  3.   
  4. public void onClick(View v){  
  5.         if(wifiManager.isWifiEnabled()){  
  6.             wifiManager.setWifiEnabled(false);  
  7.         }else{  
  8.             wifiManager.setWifiEnabled(true);  
  9.         }  
  10. }  

(3)开关移动网络。这个比较复杂,由于ConnectivityManager的setMobileDataEnabled函数是隐藏的,所以必须采用JAVA函数反射来调用到(JAVA反射相关内容可以参见他人的博文http://write.blog.csdn.net/postedit/8501773,目前会用但是理解不透)。

       定义全局变量

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. Context context = this;  
  2. ConnectivityManager manager;  
  3. TextView display;  

       页面的onCreate函数初始化

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);    
  2. if(manager == null)  
  3.     return;  
  4. display = (TextView)findViewById(R.id.testview1);   //提示当前移动网络状态  

        反射函数

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public boolean invokeMethod(String methodName,Object[]  arg) throws Exception {  
  2.     Class ownerClass = manager.getClass();  
  3.         Class[]  argsClass = null;  
  4.         if (arg != null) {  
  5.             argsClass = new Class[1];  
  6.             argsClass[0] = arg.getClass();  
  7.         }  
  8.         Method method = ownerClass.getMethod(methodName, argsClass);          
  9.         Boolean isOpen = (Boolean) method.invoke(manager, arg);  
  10.         return isOpen;  
  11. }  
  12.       
  13. public Object invokeBooleanArgMethod(String methodName,boolean value) throws Exception {  
  14.         Class ownerClass = manager.getClass();  
  15.         Class[]  argsClass = new Class[1];  
  16.         argsClass[0] = boolean.class;  
  17.         Method method = ownerClass.getMethod(methodName,argsClass);  
  18.         return method.invoke(manager, value);  
  19. }  

     反复单击一个按钮,可以看到移动网络在开关切换,从状态栏图标可以看出,从页面的textview文本也可以看出是对应的。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public void onClick(View v){  
  2.     //Log.i("zhangcheng","click");  
  3.     Object[] arg = null;  
  4.       try {  
  5.           boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled", arg);  
  6.           if(!isMobileDataEnable){  
  7.               invokeBooleanArgMethod("setMobileDataEnabled", true);  
  8.               display.setText("MOBILE NET ON");  
  9.           }  
  10.           else{  
  11.               invokeBooleanArgMethod("setMobileDataEnabled", false);  
  12.               display.setText("MOBILE NET OFF");  
  13.           }  
  14.       } catch (Exception e) {  
  15.        // TODO Auto-generated catch block  
  16.           e.printStackTrace();  
  17.       }  
  18. }  

需要的权限

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  2. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>  

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

 

       通过程序获取android系统手机的铃声和音量。同样,设置铃声和音量的方法也很简单!

AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
(1)通话音量

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_VOICE_CALL );   
  2. int current = mAudioManager.getStreamVolume( AudioManager.STREAM_VOICE_CALL );   
  3. Log.d(”VIOCE_CALL”, “max : ” + max + ” current : ” + current);    

(2)系统音量

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_SYSTEM );   
  2. current = mAudioManager.getStreamVolume( AudioManager.STREAM_SYSTEM );   
  3. Log.d(”SYSTEM”, “max : ” + max + ” current : ” + current);   

(3)铃声音量

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_RING );   
  2. current = mAudioManager.getStreamVolume( AudioManager.STREAM_RING );   
  3. Log.d(”RING”, “max : ” + max + ” current : ” + current);   

(4)音乐音量 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );   
  2. current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );   
  3. Log.d(”MUSIC”, “max : ” + max + ” current : ” + current);   

(5)提示声音音量

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_ALARM );   
  2. current = mAudioManager.getStreamVolume( AudioManager.STREAM_ALARM );   
  3. Log.d(”ALARM”, “max : ” + max + ” current : ” + current);    

         设置音量的方法也很简单:public void setStreamVolume(int streamType, int index, int flags)  ,其中streamType为铃声类型,例如:AudioManager.STREAM_VOICE_CALL、AudioManager.STREAM_SYSTEM等,index为音量大小,falgs为标志位。

         以下是修改音频设置:

(6)通话时设置静音

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. System.out.println("isMicrophoneMute =" + audioManager.isMicrophoneMute());  
  2. audioManager.setMicrophoneMute(!audioManager.isMicrophoneMute());  

(7)通话时设置免提

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. System.out.println("isSpeakerphoneOn =" + audioManager.isSpeakerphoneOn());  
  2. audioManager.setSpeakerphoneOn(!audioManager.isSpeakerphoneOn());  

别忘了修改的权限 <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
===========================================================================================
        设置振动:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. mVibrator = (Vibrator) mContext.getSystemService(Service.VIBRATOR_SERVICE);     
  2. long[] pattern = {150, 100}; // OFF/ON/OFF/ON...    
  3. mVibrator.vibrate(pattern, -1);  

 

参考原文:http://www.cnblogs.com/wgw8299/articles/2128202.html

参考原文:http://blog.csdn.net/comkingfly/article/details/7359950

参考原文:http://blog.csdn.net/ponderforever/article/details/7167591

参考原文:http://blog.csdn.net/gf771115/article/details/6996577

 

posted @ 2015-04-06 14:41  壮汉请留步  阅读(695)  评论(0编辑  收藏  举报