public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private int airState;
private Button startButton;
private Button closeButton;
private Button rButton;
boolean state = false;
IntentFilter airIntentFilter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
airIntentFilter = new IntentFilter("android.intent.action.SERVICE_STATE");
registerReceiver(airReceiver, airIntentFilter);
state = true;
startButton = (Button) findViewById(R.id.main_send_start);
closeButton = (Button) findViewById(R.id.main_send_close);
rButton = (Button) findViewById(R.id.main_receiver);
startButton.setOnClickListener(this);
closeButton.setOnClickListener(this);
rButton.setOnClickListener(this);
}
/**
* 打开飞行模式
*
* @throws InterruptedException
*/
private void satrtAirplane() {
/*
* ContentResolver cr = getContentResolver(); if
* (android.provider.Settings.System.getString(cr,
* Settings.System.AIRPLANE_MODE_ON).equals("0")) {
* 获取当前飞行模式状态,返回的是String值0,或1. 0为关闭飞行, 1为开启飞行
*/
Log.i(TAG, "开启飞行");
Settings.System.putString(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, "1");
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
sendBroadcast(intent);
Log.i(TAG, "开启飞行执行完毕");
}
/**
* 关闭飞行模式
*/
public void closeAirplane() {
Log.i(TAG, "关闭飞行模式方法 ");
Settings.System.putString(getContentResolver(), Settings.System.AIRPLANE_MODE_ON, "0");
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
sendBroadcast(intent);
Log.i(TAG, "关闭飞行模式方法 执行完毕");
}
BroadcastReceiver airReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
airState = bundle.getInt("state");
Log.e(TAG, "飞行模式状态 1为开启状态,0为关闭状态 airState==" + airState);
switch (airState) {
case 0: // 飞行模式关闭成功状态
Toast.makeText(getApplicationContext(), "关闭状态airState=" + airState, 0).show();
Log.i(TAG, "关闭状态 airState=" + airState);
break;
case 1: // 飞行模式 关闭过程
Toast.makeText(getApplicationContext(), "开启状态airState=" + airState, 0).show();
Log.i(TAG, "开启状态 airState=" + airState);
break;
case 3: // 飞行模式开启成功
Toast.makeText(getApplicationContext(), "开启成功状态airState=" + airState, 0).show();
Log.i(TAG, "飞行模式状态开启成功 airState=" + airState);
break;
}
}
}
};
@Override
public void onClick(View v) {
// TODO
switch (v.getId()) {
case R.id.main_send_start:
satrtAirplane();
break;
case R.id.main_send_close:
closeAirplane();
break;
case R.id.main_receiver:
if (state) {
unregisterReceiver(airReceiver);
state = false;
} else {
registerReceiver(airReceiver, airIntentFilter);
state = true;
}
break;
default:
break;
}
}
}
个人飞行模式小记:
每次注册飞行模式广播,系统会自动返回当前的 飞行模式状态
当飞行模式未开启:
1点击开启后,会接收到广播 airState=3飞行开启成功
2 点击关闭后,系统无反应
3 点击取消注册广播,广播关闭
当飞行模式开启过程中:
1点击开启,系统无反应,直至开启成功 ,接收到 3
2点击关闭后,系统 关闭飞行模式
当飞行模式开启:
1 点击开启,系统无反应
2 点击关闭后,系统 关闭飞行模式依次 返回 1 0 0 0
当飞行模式关闭过程中: 1点击开启后,会接收到广播 airState=3飞行开启成功 2 点击关闭后,系统 继续关闭过程