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

在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;

示列代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  2. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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;

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

3. 屏幕旋转开关:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

4. 同步开关:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  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" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

5. 亮度设置开关:

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

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.WRITE_SETTINGS" />
  2. <uses-permission android:name="android.permission.DEVICE_POWER" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.DEVICE_POWER" />

6. 飞行模式开关:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

7. 移动数据流量开关:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_APN_SETTINGS" />

8. 静音模式开关:

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

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

示例代码如下:

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

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

<-----以下的开关设置实现需要有系统的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签名;

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  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" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

10. 锁屏:

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

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

示例代码:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.USES_POLICY_FORCE_LOCK" />
  2. <uses-permission android:name="android.permission.DEVICE_POWER" />
<uses-permission android:name="android.permission.USES_POLICY_FORCE_LOCK" />
<uses-permission android:name="android.permission.DEVICE_POWER" />

11. 重启:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.REBOOT"/>
 <uses-permission android:name="android.permission.REBOOT"/>

12. 关机:

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

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

示例代码如下:

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

权限添加:

[html] view plaincopyprint?
  1. <uses-permission android:name="android.permission.SHUTDOWN" />
 <uses-permission android:name="android.permission.SHUTDOWN" />

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

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

Android的5种快捷开关的实现相关推荐

  1. android 获取快捷开关_干货水帖:Android 6.0 如何从快速开关面板启动微信扫一扫?...

    自从 iOS 开放了 Widget 接口之后,很多「勇士」就探索 Widget 的各种可能性.比如前段时间很火的 Steve,让你不开锁屏就能玩到 Chrome 中内置的恐龙跳小游戏. iOS 的 W ...

  2. Android通知栏增加快捷开关的技术实现

    我们通常可以在通知栏上看到"飞行模式"."移动数据"."屏幕录制"等开关按钮,这些按钮都属于通知栏上的快捷开关,点击快捷开关可以轻易调用某种 ...

  3. Android 9.0 SystemUI 下拉状态栏快捷开关

    SystemUI 下拉状态栏快捷开关是 QSPanel,qs_panel.xml,@+id/quick_settings_panel,本篇文章就来看看这些快捷开关是如何呈现的以及如何新增一个快捷开关? ...

  4. android不调用系统发送短信,android之两种方式调用短信发送接口

    释放双眼,带上耳机,听听看~! 相信很多程序员在开发程序的时候都会遇到短信调用端口的情况,今天是技术狗小编为大家带来的关于android之两种方式调用短信发送接口,希望对你学习这方面知识有帮助! an ...

  5. Android开发之三种动画

    转载:http://www.cnblogs.com/angeldevil/archive/2011/12/02/2271096.html http://www.lightskystreet.com/2 ...

  6. android项目两种构建方式的整合(Eclipse/idea和Android Studio)

    android的两种构建方式 目前android主要有两种构建方式,一种基于ant(传统的),另一种是13年Google/IO上新推出基于Gralde的构建(Android Studio).从sdk的 ...

  7. android物联网开发技术架构,Android 相关七种 CPU 架构适配,android七种

    Android 相关七种 CPU 架构适配,android七种 转载请注明出处:http://blog.csdn.net/kester_/article/details/71055901 NDK 开发 ...

  8. Android中四种补间动画的使用示例(附代码下载)

    场景 Android中四种补间动画. 透明度渐变动画 旋转动画 缩放动画 平移动画 注: 博客: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的 ...

  9. Android AsyncTask两种线程池分析和总结

    转自:http://bbs.51cto.com/thread-1114378-1-1.html Android AsyncTask两种线程池分析和总结 (一)    前言 在android Async ...

  10. 你都知道么?Android中21种drawable标签大全

    前言 我们在drawable目录下可以创建很多自定义的资源,其中用的最多的应该就是selector和shape.目前在Android中有21种drawable标签,了解和利用这些标签对我们的开发有很大 ...

最新文章

  1. C++和Python的OpenCV中关于图像坐标的注意事项
  2. winForm调用HTTP短信接口
  3. GoWorld – 用Golang写一个分布式可扩展、可热更的游戏服务器
  4. 十天学会ASP.net
  5. 加载gif_搞笑gif:这啥情况啊?笑容加载不出来了?
  6. 谷歌浏览器安装过程-0223
  7. java jar metainf_java – 从生成的jar文件中排除META-INF / maven文件夹
  8. 语义slam_语义SLAM: 接轨深度学习的新方向
  9. 华为软件机试测试题C语言,华为软件测试面试经验
  10. 从工作组向域管理转型该如何设置?
  11. 网上花店java项目_jsp+servlet开发java web网上花店商城系统,后台可配置化,方便修改,也可修改做成其他商城类项目...
  12. [luoguP3332] [ZJOI2013]K大数查询(树套树)
  13. 物联网学什么编程语言_物联网开发用什么语言
  14. 电商数据分析师面试题分享
  15. python读取txt文档乱码解决
  16. Doris1.1.1多种异构数据源数据导入方案
  17. uniapp 网易云音乐app项目总结
  18. excel oledb mysql_excel连接数据库oledb
  19. 无法启动此程序因为计算机丢失zlib.dll,zlib1.dll怎么修复?zlib1.dll丢失解决方法及注意事项...
  20. 阿里云远程桌面无法连接怎么办

热门文章

  1. 刚入职的程序员小白你该如何提升自己?(新手看)
  2. win10任务管理器禁用_如何在Windows 10的文件资源管理器中禁用广告和通知
  3. Android 高德地图marker位置刷新操作
  4. 详细 C语言自增自减运算符区分 ++n和n++
  5. 在繁杂的网页中揪出email地址
  6. 家用千兆路由器排行榜前十名_家用路由器排名前十名
  7. arm el2与el3_ARM下的EL/PL概念
  8. 硬核!深信服春招3面,终获20k入职offer!
  9. linux命令 执行间隙,linux 定时执行任务 at atq atrm命令的使用
  10. java 类型推断_Java™ 教程(类型推断)