Android笔记之飞行模式

Android笔记之飞行模式

[系统应用]核心代码:

boolean isEnabled = Settings.System.getInt(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;  
Settings.System.putInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON, isEnabled?0:1);  
Intent i=new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);  
i.putExtra("state", !isEnabled);  
sendBroadcast(i);  

但在Android4.2以上的版本,AIRPLANE_MODE_ON 从Setting.System下移到了Settings.Global下,因此该实现代码为:

boolean isEnabled = Settings.System.getInt(context.getContentResolver(), android.provider.Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
            Settings.System.putInt(context.getContentResolver(),android.provider.Settings.Global.AIRPLANE_MODE_ON, isEnabled?0:1);
Intent i=new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
i.putExtra("state", !isEnabled);
context.sendBroadcast(i);

另外在AndroidManifest.xml中需要添加permission:

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

为什么说上面的实现代码只有是系统应用能可以用呢,原因是 Intent.ACTION_AIRPLANE_MODE_CHANGED是一个受保护的广播,一般应用调用会抛出下面的安全异常:

Process: com.samsung.android.app.application, PID: 26481
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.AIRPLANE_MODE from pid=26481, uid=10148
    at android.os.Parcel.readException(Parcel.java:1620)
    at android.os.Parcel.readException(Parcel.java:1573)
    at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:3621)
    at android.app.ContextImpl.sendBroadcast(ContextImpl.java:847)
    at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:410)

而解决的办法就是把应用放到源码中去编译,并且加上下面权限:

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

当然对于一般应用来说,我们不需要像上面那样直接更改飞行模式。我们可以跳转到Setting的飞行模式设置界面来引导用户进行更改。实现代码如下:

Intent flightModeIntent = new Intent(Settings.ACTION_SETTINGS);
context.startActivity(flightModeIntent);

监听飞行模式的改变:

BroadcastReceiver  mReceiver = new AirplaneModeBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(mReceiver, intentFilter);

private class AirplaneModeBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
               // add your code here ………
            }
        }
展开阅读全文

没有更多推荐了,返回首页