【发布时间】:2012-08-19 18:04:23
【问题描述】:
在状态栏下方,有五个按钮 - Wifi、蓝牙、GPS、静音模式和自动旋转。我还没有想出一种方法来检测用户何时单击“自动旋转”按钮。
我所做的是有一个监听方向变化的服务,例如:
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
this.registerReceiver(myReceiver, intentFilter);
}
public BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
// Show a message about orientation changes.
// This method is only called when the phone is physically rotated.
}
}
}
}
上面的BroadcastReceiver只有在手机物理旋转的情况下才会起作用,但是如果在手机没有任何物理旋转的情况下点击了Auto Rotation按钮,那么BroadcastReceiver方法永远不会被调用。
我也尝试过 OrientationEventListener - 但行为与 BroadcastReceiver 方法相同。
为了设置方向,我使用了以下方法:
Settings.System.getInt(context.getContentResolver(), "accelerometer_rotation")
所以我知道有一种方法可以询问系统设置。是否有陷阱系统设置的[方向]变化的意图?我浏览了 Android 文档,但找不到 - 也许是我找错地方了,或者没有 Intent。
有谁知道如何捕捉状态栏中“自动旋转”按钮的变化?
更新 1:我正在使用的设备是:三星 Galaxy S3、三星 Galaxy S2、三星 Galaxy S 和三星 Galaxy Ace 等等。所有这些设备都运行库存 ROM,并且在状态栏下方有自动旋转按钮。
更新 2:有人建议使用 ContentObserver 来监听系统设置的变化,例如:
public class SettingsContentObserver extends ContentObserver {
public SettingsContentObserver(Handler handler) {
super(handler);
}
@Override
public boolean deliverSelfNotifications() {
return super.deliverSelfNotifications();
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Logging.writeDebug("Settings change detected: " + selfChange);
}
public void registerContentObserver(Context context) {
context.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true, this);
}
public void unregisterContentObserver(Context context) {
context.getContentResolver().unregisterContentObserver(this);
}
}
但是,我发现onChange 方法中的selfChange 变量总是返回false。
【问题讨论】:
-
Stock AOSP Android 没有您在状态栏中描述的按钮。如果您提及您正在使用的设备,这可能会有所帮助。
-
@adamp:请参阅上面我的问题中的更新信息。
-
单击该按钮是否会导致实际的方向更改(是否重置为默认/自然方向?)还是只是将设备锁定到当前方向?如果是后者,听起来您正在观察的行为正在按预期工作 - 您没有收到方向更改事件,因为方向已被锁定并且它没有改变。你想完成什么?
-
@adamp:在手机物理定向之前,没有方向是“可见的”,但是当单击按钮时它仍然启用。单击 Auto Rotation 按钮与 [在 ICS 4.0.3 上] 单击 Settings |显示 |自动旋转屏幕复选框。我试图检测何时启用/禁用方向以通过我的应用程序中的 TextView 对象提供消息。我希望这是有道理的。
-
如果您想监控该设置的更改:stackoverflow.com/questions/6190779/…
标签: android android-intent orientation broadcastreceiver listener