zoukankan      html  css  js  c++  java
  • Android快捷开关实现(转)

    在Android源码中,提供的快捷开关相对是比较少的,Android4.0系统默认提供的桌面快捷开关AppWidget上只有5种开关(分别是Wifi开关、蓝牙开关、GPS开关、同步开关、亮度设置开关)如下图所示:

           

      当然,有时候就需要开发实现承载更多的快捷开关的AppWidget来实现用户体验,所以,本文主要针对这些开关的主要代码实现来重点解决开发这些快捷开关。

      本文涉及到的快捷开关代码实现有Wifi、蓝牙、GPS、同步、亮度设置、飞行模式、移动数据流量(实现开启和关闭移动网络)、静音模式、重启、关机、锁屏、屏幕旋转等。需要注意的是:实现这些开关控制时都需要在AndroidManifest.xml文件中添加相应的权限。

         一般这些开关在被设置改变时,系统会向外界发送相应的广播。所以,当用代码实现操作这些开关时,我们可以通过动态注册广播接收器,来接收这些系统发送的状态改变广播,以此来验证我们是否正常设置改变了这些开关。

         当然,在本文以下的一些实例代码中,开关按钮也随着状态的改变而显示不同的文字,动态注册广播接收会显得有点多余,不过这只是证明系统会发送相应的广播,还应用开发还是有用处的,至少我们可以在不同的进程中监听接收这些广播。

     1. Wifi开关:

            1). Wifi开关由WifiManager这个类控制实现。

            2). 当Wifi开关改变时,系统会向外界发送广播android.net.wifi.WIFI_STATE_CHANGED;

            示列代码如下:

    1. package com.example.wst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.BroadcastReceiver;  
    5. import android.content.Context;  
    6. import android.content.Intent;  
    7. import android.content.IntentFilter;  
    8. import android.net.wifi.WifiManager;  
    9. import android.os.Bundle;  
    10. import android.view.View;  
    11. import android.view.View.OnClickListener;  
    12. import android.widget.Button;  
    13. import android.widget.Toast;  
    14.   
    15. public class WifiSwitchTest extends Activity implements OnClickListener  
    16. {  
    17.     private WifiManager mWifiManager;  
    18.     private Button mWifiButton;  
    19.     //Wifi设置改变系统发送的广播  
    20.     public static final String WIFI_STATE_CHANGED = "android.net.wifi.WIFI_STATE_CHANGED";  
    21.     private TestChange mTestChange;  
    22.     private IntentFilter mIntentFilter;  
    23.     /** Called when the activity is first created. */  
    24.     @Override  
    25.     public void onCreate(Bundle savedInstanceState)   
    26.     {  
    27.         super.onCreate(savedInstanceState);  
    28.         setContentView(R.layout.main);  
    29.         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
    30.         mTestChange = new TestChange();  
    31.         mIntentFilter = new IntentFilter();  
    32.         // 添加广播接收器过滤的广播  
    33.         mIntentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");  
    34.           
    35.         mWifiButton = (Button)findViewById(R.id.wifi);  
    36.         refreshButton();  
    37.         mWifiButton.setOnClickListener(this);  
    38.     }  
    39.       
    40.     @Override  
    41.     protected void onDestroy()   
    42.     {  
    43.         // TODO Auto-generated method stub  
    44.         super.onDestroy();  
    45.         // 解除广播接收器  
    46.         unregisterReceiver(mTestChange);  
    47.     }  
    48.   
    49.     @Override  
    50.     protected void onResume()  
    51.     {  
    52.         // TODO Auto-generated method stub  
    53.         super.onResume();  
    54.         // 注册广播接收器  
    55.         registerReceiver(mTestChange, mIntentFilter);  
    56.     }  
    57.       
    58.     //更新按钮  
    59.     private void refreshButton()  
    60.     {  
    61.         mWifiButton.setText(mWifiManager.isWifiEnabled() ? R.string.wifi_off : R.string.wifi_on);  
    62.     }  
    63.       
    64.     @Override  
    65.     public void onClick(View v)  
    66.     {  
    67.         // TODO Auto-generated method stub  
    68.         if (mWifiManager.isWifiEnabled())  
    69.         {  
    70.             //关闭Wifi,按钮显示开启  
    71.             mWifiManager.setWifiEnabled(false);  
    72.         }  
    73.         else  
    74.         {  
    75.             //开启Wifi,按钮显示关闭  
    76.             mWifiManager.setWifiEnabled(true);  
    77.         }  
    78.     }  
    79.       
    80.     private class TestChange extends BroadcastReceiver  
    81.     {  
    82.   
    83.         @Override  
    84.         public void onReceive(Context context, Intent intent)   
    85.         {  
    86.             // TODO Auto-generated method stub  
    87.             String action = intent.getAction();  
    88.   
    89.             if (WIFI_STATE_CHANGED.equals(action))  
    90.             {  
    91.                 refreshButton();  
    92.                 Toast.makeText(WifiSwitchTest.this, "Wifi设置有改变",  
    93.                         Toast.LENGTH_SHORT).show();  
    94.             }  
    95.         }  
    96.   
    97.     }  
    98. }  

        权限添加:

    1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
    2. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />  

      2. 蓝牙开关:

          1). 蓝牙开关主要调用BluetoothAdapter相关方法实现

          2). 蓝牙有四种状态:正在打开、打开、正在关闭、关闭

          3). 蓝牙状态改变,系统向外界发送广播android.bluetooth.adapter.action.STATE_CHANGED或android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED;

           示例代码如下:

    1. package com.example.bts;  
    2.   
    3. import android.app.Activity;  
    4. import android.bluetooth.BluetoothAdapter;  
    5. import android.content.BroadcastReceiver;  
    6. import android.content.Context;  
    7. import android.content.Intent;  
    8. import android.content.IntentFilter;  
    9. import android.os.Bundle;  
    10. import android.view.View;  
    11. import android.view.View.OnClickListener;  
    12. import android.widget.Button;  
    13. import android.widget.Toast;  
    14.   
    15. public class BluetoothSwitch extends Activity implements OnClickListener  
    16. {  
    17.     private Button mBluetooth;  
    18.     private BluetoothAdapter mBluetoothAdapter;  
    19.     private TestChange mTestChange;  
    20.     private IntentFilter mIntentFilter;  
    21.     public static final String BLUETOOTH_STATE_CHANGED = "android.bluetooth.adapter.action.STATE_CHANGED";  
    22.     private static final String BLUETOOTH_ACTION = "android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED";  
    23.     /** Called when the activity is first created. */  
    24.     @Override  
    25.     public void onCreate(Bundle savedInstanceState)   
    26.     {  
    27.         super.onCreate(savedInstanceState);  
    28.         setContentView(R.layout.main);  
    29.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  
    30.         mTestChange = new TestChange();  
    31.         mIntentFilter = new IntentFilter();  
    32.         // 添加广播接收器过滤的广播  
    33.         mIntentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");  
    34.         mIntentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");  
    35.           
    36.         mBluetooth = (Button)findViewById(R.id.blue);  
    37.         refreshButton();  
    38.         mBluetooth.setOnClickListener(this);  
    39.           
    40.     }  
    41.       
    42.     @Override  
    43.     protected void onDestroy()   
    44.     {  
    45.         // TODO Auto-generated method stub  
    46.         super.onDestroy();  
    47.         // 解除广播接收器  
    48.         unregisterReceiver(mTestChange);  
    49.     }  
    50.   
    51.     @Override  
    52.     protected void onResume()  
    53.     {  
    54.         // TODO Auto-generated method stub  
    55.         super.onResume();  
    56.         // 注册广播接收器  
    57.         registerReceiver(mTestChange, mIntentFilter);  
    58.     }  
    59.       
    60.     //更新按钮状态  
    61.     private void refreshButton()  
    62.     {  
    63.         switch (getBluetoothStatus())   
    64.         {  
    65.         case BluetoothAdapter.STATE_ON:  
    66.              mBluetooth.setText(R.string.off);  
    67.             break;  
    68.         case BluetoothAdapter.STATE_TURNING_ON:  
    69.             mBluetooth.setText(R.string.oning);  
    70.             break;  
    71.         case BluetoothAdapter.STATE_OFF:  
    72.             mBluetooth.setText(R.string.on);  
    73.             break;  
    74.         case BluetoothAdapter.STATE_TURNING_OFF:  
    75.             mBluetooth.setText(R.string.offing);  
    76.             break;  
    77.         }  
    78.     }  
    79.       
    80.     //获取蓝牙当前状态  
    81.     private int getBluetoothStatus()  
    82.     {  
    83.         return mBluetoothAdapter.getState();  
    84.     }  
    85.       
    86.     //设置蓝牙开关  
    87.     private void setBluetoothStatus()  
    88.     {  
    89.         switch (getBluetoothStatus())   
    90.         {  
    91.         case BluetoothAdapter.STATE_ON:  
    92.              mBluetoothAdapter.disable();  
    93.             break;  
    94.         case BluetoothAdapter.STATE_TURNING_ON:  
    95.             mBluetoothAdapter.disable();  
    96.             break;  
    97.         case BluetoothAdapter.STATE_OFF:  
    98.             mBluetoothAdapter.enable();  
    99.             break;  
    100.         case BluetoothAdapter.STATE_TURNING_OFF:  
    101.             mBluetoothAdapter.enable();  
    102.             break;  
    103.         }  
    104.     }  
    105.     @Override  
    106.     public void onClick(View v)   
    107.     {  
    108.         // TODO Auto-generated method stub  
    109.         setBluetoothStatus();  
    110.     }  
    111.       
    112.     private class TestChange extends BroadcastReceiver  
    113.     {  
    114.   
    115.         @Override  
    116.         public void onReceive(Context context, Intent intent)   
    117.         {  
    118.             // TODO Auto-generated method stub  
    119.             String action = intent.getAction();  
    120.   
    121.             if (BLUETOOTH_STATE_CHANGED.equals(action) || BLUETOOTH_ACTION.equals(action))  
    122.             {  
    123.                 Toast.makeText(BluetoothSwitch.this, "蓝牙模式设置有改变",  
    124.                         Toast.LENGTH_SHORT).show();  
    125.                 //动态刷新按钮  
    126.                 refreshButton();  
    127.             }  
    128.         }  
    129.   
    130.     }  
    131.       
    132. }  

          权限添加:

    1. <uses-permission android:name="android.permission.BLUETOOTH" />  
    2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />  

      3. 屏幕旋转开关:

          1). 屏幕旋转开关设置主要调用android.provider.Settings.System的putInt和getInt方法实现。

          2). 通过ContentObserver来动态观察屏幕旋转设置的改变。

             示例代码如下:

    1. package com.example.srs;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.ContentResolver;  
    5. import android.content.Context;  
    6. import android.database.ContentObserver;  
    7. import android.net.Uri;  
    8. import android.os.Bundle;  
    9. import android.os.Handler;  
    10. import android.provider.Settings;  
    11. import android.provider.Settings.SettingNotFoundException;  
    12. import android.util.Log;  
    13. import android.view.View;  
    14. import android.view.View.OnClickListener;  
    15. import android.widget.Button;  
    16. import android.widget.Toast;  
    17.   
    18. public class ScreenRotationSwitch extends Activity implements OnClickListener  
    19. {  
    20.     private Button mRotationButton;  
    21.   
    22.     private RotationObserver mRotationObserver;  
    23.     /** Called when the activity is first created. */  
    24.     @Override  
    25.     public void onCreate(Bundle savedInstanceState)  
    26.     {  
    27.         super.onCreate(savedInstanceState);  
    28.         setContentView(R.layout.main);  
    29.         //创建观察类对象  
    30.         mRotationObserver = new RotationObserver(new Handler());  
    31.           
    32.         mRotationButton = (Button) findViewById(R.id.rotation);  
    33.         refreshButton();  
    34.         mRotationButton.setOnClickListener(this);  
    35.     }  
    36.   
    37.       
    38.     @Override  
    39.     protected void onDestroy() {  
    40.         // TODO Auto-generated method stub  
    41.         super.onDestroy();  
    42.         //解除观察变化  
    43.         mRotationObserver.stopObserver();  
    44.     }  
    45.   
    46.   
    47.     @Override  
    48.     protected void onResume() {  
    49.         // TODO Auto-generated method stub  
    50.         super.onResume();  
    51.         //注册观察变化  
    52.         mRotationObserver.startObserver();  
    53.     }  
    54.   
    55.   
    56.     //更新按钮状态  
    57.     private void refreshButton()  
    58.     {  
    59.         if (getRotationStatus(this) == 1)  
    60.         {  
    61.             mRotationButton.setText(R.string.rotation_off);  
    62.         }  
    63.         else  
    64.         {  
    65.             mRotationButton.setText(R.string.rotation_on);  
    66.         }  
    67.     }  
    68.   
    69.     //得到屏幕旋转的状态  
    70.     private int getRotationStatus(Context context)  
    71.     {  
    72.         int status = 0;  
    73.         try  
    74.         {  
    75.             status = android.provider.Settings.System.getInt(context.getContentResolver(),  
    76.                     android.provider.Settings.System.ACCELEROMETER_ROTATION);  
    77.         }  
    78.         catch (SettingNotFoundException e)  
    79.         {  
    80.             // TODO Auto-generated catch block  
    81.             e.printStackTrace();  
    82.         }  
    83.         return status;  
    84.     }  
    85.   
    86.     private void setRotationStatus(ContentResolver resolver, int status)  
    87.     {  
    88.         //得到uri  
    89.         Uri uri = android.provider.Settings.System.getUriFor("accelerometer_rotation");  
    90.         //沟通设置status的值改变屏幕旋转设置  
    91.         android.provider.Settings.System.putInt(resolver, "accelerometer_rotation", status);  
    92.         //通知改变  
    93.         resolver.notifyChange(uri, null);  
    94.     }  
    95.   
    96.     @Override  
    97.     public void onClick(View v)  
    98.     {  
    99.         // TODO Auto-generated method stub  
    100.   
    101.         if (getRotationStatus(this) == 1)  
    102.         {  
    103.            
    104.             setRotationStatus(getContentResolver(), 0);  
    105.         }  
    106.         else  
    107.         {  
    108.             setRotationStatus(getContentResolver(), 1);  
    109.         }  
    110.     }  
    111.       
    112.     //观察屏幕旋转设置变化,类似于注册动态广播监听变化机制  
    113.     private class RotationObserver extends ContentObserver  
    114.     {  
    115.         ContentResolver mResolver;  
    116.           
    117.         public RotationObserver(Handler handler)   
    118.         {  
    119.             super(handler);  
    120.             mResolver = getContentResolver();  
    121.             // TODO Auto-generated constructor stub  
    122.         }  
    123.   
    124.         //屏幕旋转设置改变时调用  
    125.         @Override  
    126.         public void onChange(boolean selfChange)   
    127.         {  
    128.             // TODO Auto-generated method stub  
    129.             super.onChange(selfChange);  
    130.             //更新按钮状态  
    131.             refreshButton();  
    132.             Toast.makeText(ScreenRotationSwitch.this, "旋转屏幕设置有变化",  
    133.                     Toast.LENGTH_SHORT).show();  
    134.         }  
    135.   
    136.         public void startObserver()  
    137.         {  
    138.             mResolver.registerContentObserver(Settings.System  
    139.                     .getUriFor(Settings.System.ACCELEROMETER_ROTATION), false,  
    140.                     this);  
    141.         }  
    142.      
    143.         public void stopObserver()  
    144.         {  
    145.             mResolver.unregisterContentObserver(this);  
    146.         }  
    147.     }  
    148. }  

         权限添加:

    1. <uses-permission android:name="android.permission.WRITE_SETTINGS"/>  

      4. 同步开关:

         1). 同步开关设置主要由ContentResolver类(抽象类)的静态函数来实现;

         2). 当同步模式改变时,系统会向外界发送广播com.android.sync.SYNC_CONN_STATUS_CHANGED;

         示例代码如下:

    1. package com.example.sst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.BroadcastReceiver;  
    5. import android.content.ContentResolver;  
    6. import android.content.Context;  
    7. import android.content.Intent;  
    8. import android.content.IntentFilter;  
    9. import android.net.ConnectivityManager;  
    10. import android.os.Bundle;  
    11. import android.view.View;  
    12. import android.view.View.OnClickListener;  
    13. import android.widget.Button;  
    14. import android.widget.Toast;  
    15.   
    16. public class SyncSwitchTest extends Activity implements OnClickListener  
    17. {  
    18.     private Button mSyncButton;  
    19.     private TestChange mTestChange;  
    20.     private IntentFilter mIntentFilter;  
    21.       
    22.     //同步模式改变系统发送的广播  
    23.     private static final String SYNC_CONN_STATUS_CHANGED = "com.android.sync.SYNC_CONN_STATUS_CHANGED";  
    24.     /** Called when the activity is first created. */  
    25.       
    26.     @Override  
    27.     public void onCreate(Bundle savedInstanceState)   
    28.     {  
    29.         super.onCreate(savedInstanceState);  
    30.         setContentView(R.layout.main);  
    31.         mTestChange = new TestChange();  
    32.         mIntentFilter = new IntentFilter();  
    33.         //添加广播接收器过滤的广播  
    34.         mIntentFilter.addAction("com.android.sync.SYNC_CONN_STATUS_CHANGED");  
    35.           
    36.         mSyncButton = (Button)findViewById(R.id.sync);  
    37.         refreshButton();  
    38.           
    39.         mSyncButton.setOnClickListener(this);  
    40.     }  
    41.       
    42.     @Override  
    43.     protected void onDestroy()   
    44.     {  
    45.         // TODO Auto-generated method stub  
    46.         super.onDestroy();  
    47.         //解除广播接收器  
    48.         unregisterReceiver(mTestChange);  
    49.     }  
    50.   
    51.   
    52.     @Override  
    53.     protected void onResume() {  
    54.         // TODO Auto-generated method stub  
    55.         super.onResume();  
    56.         //注册广播接收器  
    57.         registerReceiver(mTestChange, mIntentFilter);  
    58.     }  
    59.       
    60.     //更新按钮状态  
    61.     private void refreshButton()  
    62.     {  
    63.         mSyncButton.setText(getSyncStatus(this) ? R.string.sync_off : R.string.sync_on);  
    64.     }  
    65.       
    66.     private boolean getSyncStatus(Context context)  
    67.     {  
    68.         ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
    69.         return connManager.getBackgroundDataSetting() && ContentResolver.getMasterSyncAutomatically();  
    70.     }  
    71.       
    72.     private void setSyncStatus(boolean enbled)  
    73.     {  
    74.         /*getMasterSyncAutomatically和setMasterSyncAutomatically为抽象类ContentResolver的静态函数, 
    75.          * 所以可以直接通过类来调用 
    76.          */  
    77.         ContentResolver.setMasterSyncAutomatically(enbled);  
    78.     }  
    79.       
    80.     @Override  
    81.     public void onClick(View v)  
    82.     {  
    83.         // TODO Auto-generated method stub  
    84.         if(getSyncStatus(this))  
    85.         {  
    86.             setSyncStatus(false);  
    87.         }  
    88.         else  
    89.         {  
    90.             setSyncStatus(true);  
    91.         }  
    92.     }  
    93.       
    94.     private class TestChange extends BroadcastReceiver  
    95.     {  
    96.   
    97.         @Override  
    98.         public void onReceive(Context context, Intent intent)   
    99.         {  
    100.             // TODO Auto-generated method stub  
    101.             String action = intent.getAction();  
    102.               
    103.             if (SYNC_CONN_STATUS_CHANGED.equals(action))  
    104.             {  
    105.                 refreshButton();  
    106.                 Toast.makeText(SyncSwitchTest.this, "同步模式设置有改变", Toast.LENGTH_SHORT).show();  
    107.             }  
    108.         }  
    109.           
    110.     }  
    111. }  

         权限添加:

    1. <uses-permission android:name="android.permission.READ_SYNC_STATS" />  
    2. <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />  
    3.  <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />  

      5. 亮度设置开关:

         1). 亮度设置的主要调用Settings.System的putInt和getInt方法来处理,已经调用PowerManager的setBacklightBrightness方法来实现调节手机亮度。

         2). PowerManager的setBacklightBrightness的方法是隐藏的,通过反射来调用实现。

         3). 通过ContentObserver来动态观察亮度设置的改变。

          示例代码如下:

    1. package com.example.bs;  
    2.   
    3. import java.lang.reflect.Field;  
    4. import java.lang.reflect.InvocationTargetException;  
    5. import java.lang.reflect.Method;  
    6. import android.app.Activity;  
    7. import android.content.ContentResolver;  
    8. import android.content.Context;  
    9. import android.database.ContentObserver;  
    10. import android.os.Bundle;  
    11. import android.os.Handler;  
    12. import android.os.PowerManager;  
    13. import android.provider.Settings;  
    14. import android.provider.Settings.SettingNotFoundException;  
    15. import android.view.View;  
    16. import android.view.View.OnClickListener;  
    17. import android.widget.Button;  
    18. import android.widget.Toast;  
    19.   
    20. public class BrightnessSwitch extends Activity implements OnClickListener  
    21. {  
    22.     private Button mBrightness;  
    23.     private static final int LIGHT_NORMAL = 64;  
    24.     private static final int LIGHT_50_PERCENT = 127;  
    25.     private static final int LIGHT_75_PERCENT = 191;  
    26.     private static final int LIGHT_100_PERCENT = 255;  
    27.     private static final int LIGHT_AUTO = 0;  
    28.     private static final int LIGHT_ERR = -1;  
    29.       
    30.     private BrightObserver mBrightObserver;  
    31.     private PowerManager mPowerManager;  
    32.       
    33.     /** Called when the activity is first created. */  
    34.     @Override  
    35.     public void onCreate(Bundle savedInstanceState)   
    36.     {  
    37.         super.onCreate(savedInstanceState);  
    38.         setContentView(R.layout.main);  
    39.         mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);  
    40.           
    41.         mBrightObserver = new BrightObserver(new Handler());  
    42.           
    43.         mBrightness = (Button)findViewById(R.id.bright);     
    44.         refreshButton();  
    45.         mBrightness.setOnClickListener(this);  
    46.     }  
    47.   
    48.       
    49.     @Override  
    50.     protected void onDestroy()   
    51.     {  
    52.         // TODO Auto-generated method stub  
    53.         super.onDestroy();  
    54.         mBrightObserver.stopObserver();  
    55.     }  
    56.   
    57.   
    58.     @Override  
    59.     protected void onResume()   
    60.     {  
    61.         // TODO Auto-generated method stub  
    62.         super.onResume();  
    63.         mBrightObserver.startObserver();  
    64.     }  
    65.       
    66.     //更新按钮  
    67.     private void refreshButton()  
    68.     {  
    69.         switch (getBrightStatus())   
    70.         {  
    71.         case LIGHT_NORMAL:  
    72.             mBrightness.setText(R.string.light_50percent);  
    73.             break;  
    74.         case LIGHT_50_PERCENT:  
    75.             mBrightness.setText(R.string.light_75percent);  
    76.             break;  
    77.         case LIGHT_75_PERCENT:  
    78.             mBrightness.setText(R.string.light_100percent);  
    79.             break;  
    80.         case LIGHT_100_PERCENT:  
    81.             mBrightness.setText(R.string.light_auto);  
    82.             break;  
    83.         case LIGHT_AUTO:  
    84.             mBrightness.setText(R.string.light_normal);  
    85.             break;  
    86.         case LIGHT_ERR:  
    87.             mBrightness.setText(R.string.light_err);  
    88.             break;  
    89.         }  
    90.     }  
    91.       
    92.     //得到当前亮度值状态  
    93.     private int getBrightStatus()  
    94.     {  
    95.   
    96.         // TODO Auto-generated method stub  
    97.         int light = 0;  
    98.         boolean auto = false;  
    99.         ContentResolver cr = getContentResolver();  
    100.           
    101.         try   
    102.         {  
    103.             auto = Settings.System.getInt(cr,  
    104.                     Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;  
    105.             if (!auto)   
    106.             {  
    107.                 light = android.provider.Settings.System.getInt(cr,  
    108.                         Settings.System.SCREEN_BRIGHTNESS, -1);  
    109.                 if (light > 0 && light <= LIGHT_NORMAL)   
    110.                 {  
    111.                     return LIGHT_NORMAL;  
    112.                 }  
    113.                 else if (light > LIGHT_NORMAL && light <= LIGHT_50_PERCENT)   
    114.                 {  
    115.                     return LIGHT_50_PERCENT;  
    116.                 }   
    117.                 else if (light > LIGHT_50_PERCENT && light <= LIGHT_75_PERCENT)   
    118.                 {  
    119.                     return LIGHT_75_PERCENT;  
    120.                 }   
    121.                 else if (light > LIGHT_75_PERCENT && light <= LIGHT_100_PERCENT)  
    122.                 {  
    123.                     return LIGHT_100_PERCENT;  
    124.                 }  
    125.             }   
    126.             else   
    127.             {  
    128.                 return LIGHT_AUTO;  
    129.             }  
    130.         }   
    131.         catch (SettingNotFoundException e1)   
    132.         {  
    133.             // TODO Auto-generated catch block  
    134.             e1.printStackTrace();  
    135.         }  
    136.         return LIGHT_ERR;  
    137.       
    138.     }  
    139.       
    140.     private void setBrightStatus()  
    141.     {  
    142.         int light = 0;  
    143.           
    144.         switch (getBrightStatus())  
    145.         {  
    146.         case LIGHT_NORMAL:  
    147.             light = LIGHT_50_PERCENT - 1;  
    148.             break;  
    149.         case LIGHT_50_PERCENT:  
    150.             light = LIGHT_75_PERCENT - 1;  
    151.             break;  
    152.         case LIGHT_75_PERCENT:  
    153.             light = LIGHT_100_PERCENT - 1;  
    154.             break;  
    155.         case LIGHT_100_PERCENT:  
    156.             startAutoBrightness(getContentResolver());  
    157.             break;  
    158.         case LIGHT_AUTO:  
    159.             light = LIGHT_NORMAL - 1;  
    160.             stopAutoBrightness(getContentResolver());  
    161.             break;  
    162.         case LIGHT_ERR:  
    163.             light = LIGHT_NORMAL - 1;  
    164.             break;  
    165.           
    166.         }  
    167.           
    168.         setLight(light);  
    169.         setScreenLightValue(getContentResolver(), light);  
    170.     }  
    171.       
    172.     /*因为PowerManager提供的函数setBacklightBrightness接口是隐藏的, 
    173.      * 所以在基于第三方开发调用该函数时,只能通过反射实现在运行时调用 
    174.      */  
    175.     private void setLight(int light)  
    176.     {  
    177.         try  
    178.         {  
    179.             //得到PowerManager类对应的Class对象  
    180.             Class<?> pmClass = Class.forName(mPowerManager.getClass().getName());  
    181.             //得到PowerManager类中的成员mService(mService为PowerManagerService类型)  
    182.             Field field = pmClass.getDeclaredField("mService");  
    183.             field.setAccessible(true);  
    184.             //实例化mService  
    185.             Object iPM = field.get(mPowerManager);  
    186.             //得到PowerManagerService对应的Class对象  
    187.             Class<?> iPMClass = Class.forName(iPM.getClass().getName());  
    188.             /*得到PowerManagerService的函数setBacklightBrightness对应的Method对象, 
    189.              * PowerManager的函数setBacklightBrightness实现在PowerManagerService中 
    190.              */  
    191.             Method method = iPMClass.getDeclaredMethod("setBacklightBrightness", int.class);  
    192.             method.setAccessible(true);  
    193.             //调用实现PowerManagerService的setBacklightBrightness  
    194.             method.invoke(iPM, light);  
    195.         }  
    196.         catch (ClassNotFoundException e)  
    197.         {  
    198.             // TODO Auto-generated catch block  
    199.             e.printStackTrace();  
    200.         }  
    201.         catch (NoSuchFieldException e)  
    202.         {  
    203.             // TODO Auto-generated catch block  
    204.             e.printStackTrace();  
    205.         }  
    206.         catch (IllegalArgumentException e)  
    207.         {  
    208.             // TODO Auto-generated catch block  
    209.             e.printStackTrace();  
    210.         }  
    211.         catch (IllegalAccessException e)  
    212.         {  
    213.             // TODO Auto-generated catch block  
    214.             e.printStackTrace();  
    215.         }  
    216.         catch (NoSuchMethodException e)  
    217.         {  
    218.             // TODO Auto-generated catch block  
    219.             e.printStackTrace();  
    220.         }  
    221.         catch (InvocationTargetException e)  
    222.         {  
    223.             // TODO Auto-generated catch block  
    224.             e.printStackTrace();  
    225.         }  
    226.   
    227.     }  
    228.       
    229.     @Override  
    230.     public void onClick(View v)   
    231.     {  
    232.         // TODO Auto-generated method stub  
    233.         setBrightStatus();  
    234.     }  
    235.       
    236.     //启动自动调节亮度  
    237.     public void startAutoBrightness(ContentResolver cr)   
    238.     {  
    239.         Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE,  
    240.                 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);  
    241.     }  
    242.       
    243.     //关闭自动调节亮度  
    244.     public void stopAutoBrightness(ContentResolver cr)   
    245.     {  
    246.         Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE,  
    247.                 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);  
    248.     }  
    249.       
    250.     //设置改变亮度值  
    251.     public void setScreenLightValue(ContentResolver resolver, int value)  
    252.     {  
    253.         android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS,  
    254.                 value);  
    255.     }  
    256.       
    257.     private class BrightObserver extends ContentObserver  
    258.     {  
    259.         ContentResolver mResolver;  
    260.           
    261.         public BrightObserver(Handler handler)  
    262.         {  
    263.             super(handler);  
    264.             mResolver = getContentResolver();  
    265.         }  
    266.   
    267.         @Override  
    268.         public void onChange(boolean selfChange)   
    269.         {  
    270.             // TODO Auto-generated method stub  
    271.             super.onChange(selfChange);  
    272.             refreshButton();  
    273.             Toast.makeText(BrightnessSwitch.this, "亮度设置有改变", Toast.LENGTH_SHORT).show();  
    274.         }  
    275.           
    276.         //注册观察  
    277.         public void startObserver()  
    278.         {  
    279.             mResolver.registerContentObserver(Settings.System  
    280.                     .getUriFor(Settings.System.SCREEN_BRIGHTNESS), false,  
    281.                     this);  
    282.             mResolver.registerContentObserver(Settings.System  
    283.                     .getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE), false,  
    284.                     this);  
    285.         }  
    286.           
    287.         //解除观察  
    288.         public void stopObserver()  
    289.         {  
    290.             mResolver.unregisterContentObserver(this);  
    291.         }  
    292.     }  
    293. }  

       权限添加:

    1. <uses-permission android:name="android.permission.WRITE_SETTINGS" />  
    2. <uses-permission android:name="android.permission.DEVICE_POWER" />  

      6. 飞行模式开关:

          1). 飞行模式主要是调用Settings.System的getInt和setInt方法来处理。

          2). 当飞行模式改变时,系统会向外界发送广播android.intent.action.AIRPLANE_MODE;

          示例代码如下:

    1. package com.example.apmst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.BroadcastReceiver;  
    5. import android.content.Context;  
    6. import android.content.Intent;  
    7. import android.content.IntentFilter;  
    8. import android.os.Bundle;  
    9. import android.provider.Settings;  
    10. import android.view.View;  
    11. import android.view.View.OnClickListener;  
    12. import android.widget.Button;  
    13. import android.widget.Toast;  
    14.   
    15. public class AirplaneModeSwitchTest extends Activity implements OnClickListener  
    16. {  
    17.     private Button mAirplane;  
    18.     //飞行模式设置改变系统发送的广播  
    19.     private static final String AIRPLANE_MODE = "android.intent.action.AIRPLANE_MODE";  
    20.     private TestChange mTestChange;  
    21.     private IntentFilter mIntentFilter;  
    22.     /** Called when the activity is first created. */  
    23.     @Override  
    24.     public void onCreate(Bundle savedInstanceState)   
    25.     {  
    26.         super.onCreate(savedInstanceState);  
    27.         setContentView(R.layout.main);  
    28.           
    29.         mTestChange = new TestChange();  
    30.         mIntentFilter = new IntentFilter();  
    31.         // 添加广播接收器过滤的广播  
    32.         mIntentFilter.addAction("android.intent.action.AIRPLANE_MODE");  
    33.           
    34.         mAirplane = (Button)findViewById(R.id.airplane);  
    35.         refreshButton();  
    36.           
    37.         mAirplane.setOnClickListener(this);  
    38.     }  
    39.       
    40.     @Override  
    41.     protected void onDestroy()   
    42.     {  
    43.         // TODO Auto-generated method stub  
    44.         super.onDestroy();  
    45.         // 解除广播接收器  
    46.         unregisterReceiver(mTestChange);  
    47.     }  
    48.   
    49.     @Override  
    50.     protected void onResume()  
    51.     {  
    52.         // TODO Auto-generated method stub  
    53.         super.onResume();  
    54.         // 注册广播接收器  
    55.         registerReceiver(mTestChange, mIntentFilter);  
    56.     }  
    57.   
    58.     //更新按钮状态  
    59.     private void refreshButton()  
    60.     {  
    61.        mAirplane.setText(getAirplaneModeStatus() ? R.string.airplane_off : R.string.airplane_on);  
    62.     }  
    63.       
    64.       
    65.     //获取飞行模式关闭或开启状态  
    66.     private boolean getAirplaneModeStatus()  
    67.     {  
    68.         boolean status = Settings.System.getInt(this.getContentResolver(),  
    69.                 Settings.System.AIRPLANE_MODE_ON, 0) == 1 ? true : false;  
    70.           
    71.         return status;  
    72.     }  
    73.       
    74.     //开启或关闭飞行模式  
    75.     private void setAirplaneMode(Context context, boolean enable)  
    76.     {  
    77.         Settings.System.putInt(context.getContentResolver(),  
    78.                 Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);  
    79.         Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);  
    80.         intent.putExtra("state", enable);  
    81.         context.sendBroadcast(intent);  
    82.     }  
    83.       
    84.     @Override  
    85.     public void onClick(View v)  
    86.     {  
    87.         // TODO Auto-generated method stub  
    88.         if (getAirplaneModeStatus())  
    89.         {  
    90.             setAirplaneMode(this, false);  
    91.         }  
    92.         else  
    93.         {  
    94.             setAirplaneMode(this, true);  
    95.         }  
    96.     }  
    97.       
    98.     private class TestChange extends BroadcastReceiver  
    99.     {  
    100.   
    101.         @Override  
    102.         public void onReceive(Context context, Intent intent)   
    103.         {  
    104.             // TODO Auto-generated method stub  
    105.             String action = intent.getAction();  
    106.   
    107.             if (AIRPLANE_MODE.equals(action))  
    108.             {  
    109.                 refreshButton();  
    110.                 Toast.makeText(AirplaneModeSwitchTest.this, "飞行模式设置有改变",  
    111.                         Toast.LENGTH_SHORT).show();  
    112.             }  
    113.         }  
    114.   
    115.     }  
    116. }  

         权限添加:

    1. <uses-permission android:name="android.permission.WRITE_SETTINGS" />  

      7. 移动数据流量开关:

          1). 移动数据流量由ConnectivityManager类控制实现,这个类实现设置和获取移动流量状态的方法是隐藏的,所以我们只能通过反射来实现(或者在源码下编译APK)。

         2). 相关广播为android.intent.action.ANY_DATA_STATE;

        示例代码如下:

    1. package com.example.mdst;  
    2.   
    3. import java.lang.reflect.Field;  
    4. import java.lang.reflect.InvocationTargetException;  
    5. import java.lang.reflect.Method;  
    6.   
    7. import android.app.Activity;  
    8. import android.content.BroadcastReceiver;  
    9. import android.content.Context;  
    10. import android.content.Intent;  
    11. import android.content.IntentFilter;  
    12. import android.net.ConnectivityManager;  
    13. import android.os.Bundle;  
    14. import android.view.View;  
    15. import android.view.View.OnClickListener;  
    16. import android.widget.Button;  
    17. import android.widget.Toast;  
    18.   
    19. public class MobileDataSwitchTest extends Activity implements OnClickListener  
    20. {  
    21.     private ConnectivityManager mConnectivityManager;  
    22.     private Button mMobileDataButton;  
    23.     // 移动数据设置改变系统发送的广播  
    24.     private static final String NETWORK_CHANGE = "android.intent.action.ANY_DATA_STATE";  
    25.     private TestChange mTestChange;  
    26.     private IntentFilter mIntentFilter;  
    27.   
    28.     /** Called when the activity is first created. */  
    29.     @Override  
    30.     public void onCreate(Bundle savedInstanceState)  
    31.     {  
    32.         super.onCreate(savedInstanceState);  
    33.         setContentView(R.layout.main);  
    34.   
    35.         mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
    36.           
    37.         mTestChange = new TestChange();  
    38.         mIntentFilter = new IntentFilter();  
    39.         // 添加广播接收器过滤的广播  
    40.         mIntentFilter.addAction("android.intent.action.ANY_DATA_STATE");  
    41.   
    42.         mMobileDataButton = (Button) findViewById(R.id.mobile_data);  
    43.         refreshButton();  
    44.         mMobileDataButton.setOnClickListener(this);  
    45.     }  
    46.   
    47.     @Override  
    48.     protected void onDestroy()   
    49.     {  
    50.         // TODO Auto-generated method stub  
    51.         super.onDestroy();  
    52.         // 解除广播接收器  
    53.         unregisterReceiver(mTestChange);  
    54.     }  
    55.   
    56.     @Override  
    57.     protected void onResume()  
    58.     {  
    59.         // TODO Auto-generated method stub  
    60.         super.onResume();  
    61.         // 注册广播接收器  
    62.         registerReceiver(mTestChange, mIntentFilter);  
    63.     }  
    64.   
    65.     private void refreshButton()  
    66.     {  
    67.         mMobileDataButton.setText(getMobileDataStatus() ? R.string.mobile_data_off : R.string.mobile_data_on);  
    68.     }  
    69.   
    70.     //获取移动数据开关状态  
    71.     private boolean getMobileDataStatus()  
    72.     {  
    73.         String methodName = "getMobileDataEnabled";  
    74.         Class cmClass = mConnectivityManager.getClass();  
    75.         Boolean isOpen = null;  
    76.           
    77.         try   
    78.         {  
    79.             Method method = cmClass.getMethod(methodName, null);  
    80.   
    81.             isOpen = (Boolean) method.invoke(mConnectivityManager, null);  
    82.         }   
    83.         catch (Exception e)   
    84.         {  
    85.             e.printStackTrace();  
    86.         }  
    87.         return isOpen;  
    88.     }  
    89.           
    90.     // 通过反射实现开启或关闭移动数据  
    91.     private void setMobileDataStatus(boolean enabled)   
    92.     {  
    93.         try   
    94.         {  
    95.             Class<?> conMgrClass = Class.forName(mConnectivityManager.getClass().getName());  
    96.             //得到ConnectivityManager类的成员变量mService(ConnectivityService类型)  
    97.             Field iConMgrField = conMgrClass.getDeclaredField("mService");  
    98.             iConMgrField.setAccessible(true);  
    99.             //mService成员初始化  
    100.             Object iConMgr = iConMgrField.get(mConnectivityManager);  
    101.             //得到mService对应的Class对象  
    102.             Class<?> iConMgrClass = Class.forName(iConMgr.getClass().getName());  
    103.             /*得到mService的setMobileDataEnabled(该方法在android源码的ConnectivityService类中实现), 
    104.              * 该方法的参数为布尔型,所以第二个参数为Boolean.TYPE 
    105.              */  
    106.             Method setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod(  
    107.                     "setMobileDataEnabled", Boolean.TYPE);  
    108.             setMobileDataEnabledMethod.setAccessible(true);  
    109.             /*调用ConnectivityManager的setMobileDataEnabled方法(方法是隐藏的), 
    110.              * 实际上该方法的实现是在ConnectivityService(系统服务实现类)中的 
    111.              */  
    112.             setMobileDataEnabledMethod.invoke(iConMgr, enabled);  
    113.         } catch (ClassNotFoundException e)   
    114.         {  
    115.             e.printStackTrace();  
    116.         } catch (NoSuchFieldException e)   
    117.         {  
    118.             e.printStackTrace();  
    119.         } catch (SecurityException e)   
    120.         {  
    121.             e.printStackTrace();  
    122.         } catch (NoSuchMethodException e)   
    123.         {  
    124.             e.printStackTrace();  
    125.         } catch (IllegalArgumentException e)   
    126.         {  
    127.             e.printStackTrace();  
    128.         } catch (IllegalAccessException e)   
    129.         {  
    130.             e.printStackTrace();  
    131.         } catch (InvocationTargetException e)   
    132.         {  
    133.             e.printStackTrace();  
    134.         }  
    135.     }  
    136.   
    137.     @Override  
    138.     public void onClick(View v)   
    139.     {  
    140.         // TODO Auto-generated method stub  
    141.   
    142.         if (getMobileDataStatus())  
    143.         {  
    144.             setMobileDataStatus(false);  
    145.             mMobileDataButton.setText(R.string.mobile_data_on);  
    146.         }  
    147.         else  
    148.         {  
    149.             setMobileDataStatus(true);  
    150.             mMobileDataButton.setText(R.string.mobile_data_off);  
    151.         }  
    152.     }  
    153.   
    154.     private class TestChange extends BroadcastReceiver  
    155.     {  
    156.   
    157.         @Override  
    158.         public void onReceive(Context context, Intent intent)   
    159.         {  
    160.             // TODO Auto-generated method stub  
    161.             String action = intent.getAction();  
    162.   
    163.             if (NETWORK_CHANGE.equals(action))  
    164.             {  
    165.                 Toast.makeText(MobileDataSwitchTest.this, "移动数据设置有改变",  
    166.                         Toast.LENGTH_SHORT).show();  
    167.             }  
    168.         }  
    169.   
    170.     }  
    171. }  

        权限添加:

    1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
    2. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />  
    3. <uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />  

      8. 静音模式开关:

          1). 静音模式由AudioManager控制实现,有三种状态:正常(有声音)、震动、静音

          2). 当模式改变时,系统会向外界发送广播android.media.RINGER_MODE_CHANGED;

          示例代码如下:

    1. package com.example.sst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.BroadcastReceiver;  
    5. import android.content.Context;  
    6. import android.content.Intent;  
    7. import android.content.IntentFilter;  
    8. import android.media.AudioManager;  
    9. import android.os.Bundle;  
    10. import android.view.View;  
    11. import android.view.View.OnClickListener;  
    12. import android.widget.Button;  
    13. import android.widget.Toast;  
    14.   
    15. public class SilentSwitchTes extends Activity implements OnClickListener  
    16. {  
    17.     private AudioManager mAudioManager;  
    18.     private Button mSilentButton;  
    19.     private TestChange mTestChange;  
    20.     private IntentFilter mIntentFilter;  
    21.       
    22.     //静音模式改变系统发送的广播  
    23.     public static final String RINGER_MODE_CHANGED = "android.media.RINGER_MODE_CHANGED";  
    24.     /** Called when the activity is first created. */  
    25.     @Override  
    26.     public void onCreate(Bundle savedInstanceState)   
    27.     {  
    28.         super.onCreate(savedInstanceState);  
    29.         setContentView(R.layout.main);  
    30.           
    31.         mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  
    32.         mTestChange = new TestChange();  
    33.         mIntentFilter = new IntentFilter();  
    34.         //添加广播接收器过滤的广播  
    35.         mIntentFilter.addAction("android.media.RINGER_MODE_CHANGED");  
    36.           
    37.         mSilentButton = (Button)findViewById(R.id.silent);  
    38.         refreshButton();  
    39.         mSilentButton.setOnClickListener(this);  
    40.     }  
    41.       
    42.       
    43.     @Override  
    44.     protected void onDestroy()   
    45.     {  
    46.         // TODO Auto-generated method stub  
    47.         super.onDestroy();  
    48.         //解除广播接收器  
    49.         unregisterReceiver(mTestChange);  
    50.     }  
    51.   
    52.   
    53.     @Override  
    54.     protected void onResume() {  
    55.         // TODO Auto-generated method stub  
    56.         super.onResume();  
    57.         //注册广播接收器  
    58.         registerReceiver(mTestChange, mIntentFilter);  
    59.     }  
    60.   
    61.     //更新按钮  
    62.     private void refreshButton()  
    63.     {  
    64.         switch (getSilentStatus())  
    65.         {  
    66.         case AudioManager.RINGER_MODE_SILENT:  
    67.             mSilentButton.setText(R.string.mode_vibrate);  
    68.             break;  
    69.         case AudioManager.RINGER_MODE_NORMAL:  
    70.             mSilentButton.setText(R.string.mode_silent);  
    71.             break;        
    72.         case AudioManager.RINGER_MODE_VIBRATE:  
    73.             mSilentButton.setText(R.string.mode_normal);  
    74.             break;  
    75.         }  
    76.     }  
    77.   
    78.     //获取手机当前的静音模式状态  
    79.     private int getSilentStatus()  
    80.     {  
    81.         return mAudioManager.getRingerMode();  
    82.     }  
    83.       
    84.     //设置手机的静音、正常、震动模式  
    85.     private void setSilentMode()  
    86.     {  
    87.         switch (getSilentStatus())  
    88.         {  
    89.         case AudioManager.RINGER_MODE_SILENT:  
    90.             mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);  
    91.             break;  
    92.         case AudioManager.RINGER_MODE_NORMAL:  
    93.             mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);  
    94.             break;        
    95.         case AudioManager.RINGER_MODE_VIBRATE:  
    96.             mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);  
    97.             break;  
    98.         }  
    99.     }  
    100.       
    101.     @Override  
    102.     public void onClick(View v)  
    103.     {  
    104.         // TODO Auto-generated method stub  
    105.         setSilentMode();  
    106.     }  
    107.       
    108.     private class TestChange extends BroadcastReceiver  
    109.     {  
    110.   
    111.         @Override  
    112.         public void onReceive(Context context, Intent intent)   
    113.         {  
    114.             // TODO Auto-generated method stub  
    115.             String action = intent.getAction();  
    116.               
    117.             if (RINGER_MODE_CHANGED.equals(action))  
    118.             {  
    119.                 refreshButton();  
    120.                 Toast.makeText(SilentSwitchTes.this, "静音模式设置有改变", Toast.LENGTH_SHORT).show();  
    121.             }  
    122.         }  
    123.           
    124.     }  
    125. }  

     静音模式开关设置不需要添加权限。

     

    <-----以下的开关设置实现需要有系统的UID使用Platform的apk签名,否则是没有权限调用的,会报SecurityException异常----->

                                   注:1). 可以不通过apk签名,直接在android源码下编译生成apk,再将apk安装到手机;

                              2). 如果手机有root权限,那么也不需要apk签名,直接通过adb工具将apk推到system/app目录下:操作指令为adb remount---->adb push xxx.apk system/app (注:该apk将做为系统应用)

     

       9. GPS开关:

           1). GPS开关设置的实现由Secure类的相关静态方法实现。

           2).Secure的isLocationProviderEnabled和setLocationProviderEnabled调用需要APK签名;

          示例代码如下:

    1. package com.example.gst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.Context;  
    5. import android.location.LocationManager;  
    6. import android.os.Bundle;  
    7. import android.provider.Settings.Secure;  
    8. import android.view.View;  
    9. import android.view.View.OnClickListener;  
    10. import android.widget.Button;  
    11.   
    12. public class GpsSwitchTest extends Activity implements OnClickListener  
    13. {  
    14.     private Button mGpsButton;  
    15.     /** Called when the activity is first created. */  
    16.     @Override  
    17.     public void onCreate(Bundle savedInstanceState)   
    18.     {  
    19.         super.onCreate(savedInstanceState);  
    20.         setContentView(R.layout.main);  
    21.         mGpsButton = (Button)findViewById(R.id.gps);  
    22.         refreshButton();  
    23.         mGpsButton.setOnClickListener(this);  
    24.     }  
    25.   
    26.     //根据当前的Gps状态,初始化按钮的显示  
    27.     private void refreshButton()  
    28.     {  
    29.         mGpsButton.setText(getGpsStatus(this) ? R.string.gps_off : R.string.gps_on);  
    30.     }  
    31.       
    32.     //获取Gps开启或关闭状态  
    33.     private boolean getGpsStatus(Context context)  
    34.     {  
    35.         boolean status = Secure.isLocationProviderEnabled(context.getContentResolver(),   
    36.                 LocationManager.GPS_PROVIDER);  
    37.         return status;  
    38.     }  
    39.       
    40.     //打开或关闭Gps  
    41.     private void setGpsStatus(Context context, boolean enabled)  
    42.     {  
    43.         Secure.setLocationProviderEnabled(context.getContentResolver(),  
    44.                 LocationManager.GPS_PROVIDER, enabled);  
    45.     }  
    46.       
    47.     @Override  
    48.     public void onClick(View v)  
    49.     {  
    50.         // TODO Auto-generated method stub  
    51.         if (getGpsStatus(this))  
    52.         {  
    53.             setGpsStatus(this, false);  
    54.             mGpsButton.setText(R.string.gps_on);  
    55.         }  
    56.         else  
    57.         {  
    58.             setGpsStatus(this, true);  
    59.             mGpsButton.setText(R.string.gps_off);  
    60.         }  
    61.     }  
    62. }  

           权限添加:

    1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
    2. <uses-permission android:name="android.permission.WRITE_SETTINGS" />  
    3. <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />  

      10. 锁屏:

            1). 手机进入锁屏主要由PowerManager的goToSleep函数实现。

            2). PowerManager的goToSleep调用需要apk签名。

           示例代码:

    1. package com.example.lsst;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.Context;  
    5. import android.os.Bundle;  
    6. import android.os.PowerManager;  
    7. import android.os.SystemClock;  
    8. import android.view.View;  
    9. import android.view.View.OnClickListener;  
    10. import android.widget.Button;  
    11.   
    12. public class LockScreenSwitchTest extends Activity implements OnClickListener  
    13. {  
    14.     private PowerManager mPowerManager;  
    15.     private Button mLockButton;  
    16.     /** Called when the activity is first created. */  
    17.     @Override  
    18.     public void onCreate(Bundle savedInstanceState)   
    19.     {  
    20.         super.onCreate(savedInstanceState);  
    21.         setContentView(R.layout.main);  
    22.         mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);  
    23.         mLockButton = (Button)findViewById(R.id.lock);  
    24.         mLockButton.setOnClickListener(this);  
    25.     }  
    26.       
    27.     private void lockScreen()  
    28.     {  
    29.         //强制手机进入锁屏,这时候手机会灭屏,点亮后是处于锁屏状态  
    30.         mPowerManager.goToSleep(SystemClock.uptimeMillis());  
    31.     }  
    32.     @Override  
    33.     public void onClick(View v)   
    34.     {  
    35.         // TODO Auto-generated method stub  
    36.         lockScreen();  
    37.     }  
    38. }  

           权限添加:

    1. <uses-permission android:name="android.permission.USES_POLICY_FORCE_LOCK" />  
    2. <uses-permission android:name="android.permission.DEVICE_POWER" />  

      11. 重启:

          1). 手机重启需要调用PowerManager的reboot方法实现,参数为null;

          2). 该方法的调用,需要有系统的UID使用Platform的APK签名,否则是没有权限调用的,会报SecurityException异常。

              示例代码如下:

    1. package com.example.rs;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.Context;  
    5. import android.os.Bundle;  
    6. import android.os.PowerManager;  
    7. import android.view.View;  
    8. import android.view.View.OnClickListener;  
    9. import android.widget.Button;  
    10.   
    11. public class RebootSwitch extends Activity implements OnClickListener  
    12. {  
    13.     private Button mRebootButton;  
    14.     private PowerManager mPowerManager;  
    15.     /** Called when the activity is first created. */  
    16.     @Override  
    17.     public void onCreate(Bundle savedInstanceState)   
    18.     {  
    19.         super.onCreate(savedInstanceState);  
    20.         setContentView(R.layout.main);  
    21.         mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);    
    22.         mRebootButton = (Button)findViewById(R.id.reboot);  
    23.         mRebootButton.setOnClickListener(this);  
    24.     }  
    25.       
    26.     private void reboot(String reason)  
    27.     {  
    28.         mPowerManager.reboot(null);  
    29.     }  
    30.     @Override  
    31.     public void onClick(View v)  
    32.     {  
    33.         // TODO Auto-generated method stub  
    34.         reboot(null);  
    35.     }  
    36. }  

         权限添加:

    1. <uses-permission android:name="android.permission.REBOOT"/>  

      12. 关机:

          1). 手机关机直接通过创建相关的Intent来启动一个对话框,根据对话框的确认或取消键来选择是否关机

          2). 关机实现需要apk签名。 

          示例代码如下:

    1. package com.example.sds;  
    2.   
    3. import android.app.Activity;  
    4. import android.content.Intent;  
    5. import android.os.Bundle;  
    6. import android.view.View;  
    7. import android.view.View.OnClickListener;  
    8. import android.widget.Button;  
    9.   
    10. public class ShutDownSwitch extends Activity implements OnClickListener  
    11. {  
    12.     private Button mShutDown;  
    13.     /** Called when the activity is first created. */  
    14.     @Override  
    15.     public void onCreate(Bundle savedInstanceState)   
    16.     {  
    17.         super.onCreate(savedInstanceState);  
    18.         setContentView(R.layout.main);  
    19.           
    20.         mShutDown = (Button)findViewById(R.id.shutdown);  
    21.         mShutDown.setOnClickListener(this);  
    22.           
    23.     }  
    24.     @Override  
    25.     public void onClick(View v)  
    26.     {  
    27.         // TODO Auto-generated method stub  
    28.         Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");  
    29.         intent.putExtra("android.intent.extra.KEY_CONFIRM", true);  
    30.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    31.         //弹出系统内置的对话框,选择确定关机或取消关机  
    32.         startActivity(intent);  
    33.     }  
    34.       
    35. }  

        权限添加:

    1. <uses-permission android:name="android.permission.SHUTDOWN" />  

        ok,本文的快捷开关代码实现介绍就到此结束,有了上面这些快捷开关的实现代码,那么当你想要开发一个AppWidget来承载和实现这些开关时就容易多了,至于如何去开发一个AppWidget,有兴趣的读者可以去找找相关这些方面的资料。

         相关代码下载链接:http://download.csdn.net/detail/stevenhu_223/5572751

    转载自:http://blog.csdn.net/stevenhu_223/article/details/9052083

  • 相关阅读:
    less css
    Eclipse折叠代码 coffee bytes code folding
    jTDS jdbc驱动
    十点建议:从程序员变企业家 10 Tips for Moving From Programmer to Entrepreneur
    转:Hibernate Query examples (HQL) 示例
    [转]风雨7年话3D 长篇连载
    在游戏中使用CEGUI —— 第一章(底层)
    plusMark(正号硬件性能测试器)
    我会在月底之前将CEGUI相关的东西共享出来
    近期继超女之后的2大新闻
  • 原文地址:https://www.cnblogs.com/YangBinChina/p/3949942.html
Copyright © 2011-2022 走看看