简体   繁体   English

Android飞行模式示例

[英]Android airplane mode example

I used this piece of code to turn on and off airplane mode of a Android 4.1.2 device: 我使用这段代码来打开和关闭Android 4.1.2设备的飞行模式:

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 intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
             intent.putExtra("state", !isEnabled);
             sendBroadcast(intent);

The code runs fine, but in order to fully understand why it works I have some questions. 该代码运行良好,但是为了完全理解其工作原理,我有一些疑问。

  1. Why this code doesn't work if I comment: 如果我发表评论,为什么此代码不起作用:

    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 意图意图=新意图(Intent.ACTION_AIRPLANE_MODE_CHANGED); intent.putExtra("state", !isEnabled); intent.putExtra(“ state”,!isEnabled); sendBroadcast(intent); sendBroadcast(意向);

  2. Do I have to always to broadcast an intent after I make any changes in the settings? 在设置中进行任何更改后,我是否必须始终广播意图?

Could someone please explain it in more details? 有人可以详细解释吗?

Settings.System.putInt() actually changes the int value, but the system does not notifies it. Settings.System.putInt()实际上会更改int值,但系统不会通知它。 It does not read this setting in a loop... 它不会循环读取此设置...

So, to make the system aware of that change, you send a broadcast that the system listen to, will then parse its content, notice the setting change and do stuff accordingly. 因此,要使系统知道该更改,您可以发送系统收听的广播,然后解析其内容,注意设置更改并相应地进行处理。

So you can't have this code to work without sending the broadcast, because that's what notifies the system about the change you just made. 因此,如果不发送广播,就无法使该代码正常工作,因为这正是通知系统有关您刚刚所做的更改的信息。 And yes you have to use that broadcast to notice it. 是的,您必须使用该广播来注意到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM