Android 12.0 监听手机飞行模式

1. 判断当前手机飞行模式是否开启


    /**
     * 
     * @param context
     * @return true:飞行模式开启; false:飞行模式关闭
     */
public  boolean airplaneMode(Context context) {
        return (Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1);
    }

2. 接着通过监听飞行模式提供的广播来实时监听飞行模式状态 : Intent.ACTION_AIRPLANE_MODE_CHANGED

public class MainActivity extends AppCompatActivity {

private AirplaneReceiver airplaneReceiver;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerPhoneStateReceiver();
        
    }

 private void registerPhoneStateReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);//注册广播
        airplaneReceiver = new AirplaneReceiver();
        registerReceiver(airplaneReceiver, filter);//注册监听
}


 @Override
    protected void onDestroy() {
        super.onDestroy();
        if (airplaneReceiver != null){
            unregisterReceiver(airplaneReceiver); //解除监听
            airplaneReceiver = null;
        }
        
    }
}

3. 在飞行模式状态变化时,会触发广播,接着在广播里作处理即可.

public class AirplaneReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

      String action = intent.getAction();
 if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {

     boolean airplaneMode = Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) == 1;  //获取当前飞行模式的状态
 
  }
}
}

你可能感兴趣的:(Android12,系统定制开发,Android,智能手机,android)