为什么调用Settings.Secure.putInt启用/禁用位置会暂停并恢复活动?

时间:2018-12-12 16:04:15

标签: android android-location

这可能很难给出MCVE,因为它要求应用程序在有根设备上具有WRITE_SECURE_SETTINGS许可的情况下被列入白名单,但这是可行的。

public class TestActivity extends AppCompatActivity {

    private static final String TAG = "TestingStrangeBehavior";
    private boolean locationOn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        int location = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE, LOCATION_MODE_OFF);
        locationOn = location != LOCATION_MODE_OFF;

        findViewById(R.id.toggle_location_button).setOnClickListener(view -> {
            locationOn = !locationOn;
            Log.d(TAG, "Turning location " + (locationOn?"on":"off"));
            Settings.Secure.putInt(getContentResolver(), Settings.Secure.LOCATION_MODE,
                    locationOn ? LOCATION_MODE_SENSORS_ONLY : LOCATION_MODE_OFF);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause called");
    }
}

这是布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.TestActivity">

    <Button
        android:id="@+id/toggle_location_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toggle Location"/>

</android.support.constraint.ConstraintLayout>

按“切换位置”按钮得到的输出是:

  

D / TestingStrangeBehavior:打开位置

     

D / TestingStrangeBehavior:onPause称为

     

D / TestingStrangeBehavior:onResume称为

     

D / TestingStrangeBehavior:关闭位置

     

D / TestingStrangeBehavior:onPause称为

     

D / TestingStrangeBehavior:onResume称为

如您所见,每次我打开/关闭位置时,活动都会暂停并恢复。

但是如果我putInt进入另一个字段,例如ACCESSIBILITY_ENABLED

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    int location = Settings.Secure.getInt(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0);
    locationOn = location != 0;

    findViewById(R.id.toggle_location_button).setOnClickListener(view -> {
        locationOn = !locationOn;
        Log.d(TAG, "Turning location " + (locationOn?"on":"off"));
        Settings.Secure.putInt(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED,
                locationOn ? 1 : 0);
    });
}

它不会暂停并继续活动。

这是有原因的吗?为什么切换位置会暂停并恢复活动?这是Android中的错误吗?

0 个答案:

没有答案