转自:http://www.pocketdigi.com/20110714/391.html
在Android中设置飞行状态是用BroadCast的,可以通过发送action为”Intent.ACTION_AIRPLANE_MODE_CHANGED”的广播来打开或关闭飞行模式状态.
首先,修改飞行模式需要android.permission.WRITE_SETTINGS权限,请自行添加.
下面是完整代码:
package com.hello; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import android.provider.Settings; //虽然只用到Settings.System类,但还是不建议直接导入该类,因为会跟java.lang.System同名冲突 //当然也可以不导,直接用android.provider.Settings.System public class HelloWorldActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ContentResolver cr = getContentResolver(); if(Settings.System.getString(cr,Settings.System.AIRPLANE_MODE_ON).equals("0")){ //获取当前飞行模式状态,返回的是String值0,或1.0为关闭飞行,1为开启飞行 //如果关闭飞行,则打开飞行 Settings.System.putString(cr,Settings.System.AIRPLANE_MODE_ON, "1"); Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); sendBroadcast(intent); }else{ //否则关闭飞行 Settings.System.putString(cr,Settings.System.AIRPLANE_MODE_ON, "0"); Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); sendBroadcast(intent); } } }