ContentObserver监听系统属性变化
有时候我们需要监听系统属性变化,或者通过修改系统属性的值来通知其它应用做相应的操作。
以无障碍服务的属性为例,通过ContentObserver监听其变化:Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
1、新建MyContentObserver.java类继承ContentObserver;
import android.database.ContentObserver;
import android.os.Handler;
import android.util.Log;
/**
* @author fenghaitao
* @time 2021年07月16日17:15:31
*/
public class MyContentObserver extends ContentObserver {
private final static String TAG = "MyContentObserver";
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public MyContentObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
Log.d(TAG, "onChange selfChange = " + selfChange);
super.onChange(selfChange);
}
}
2、在activity中点击按钮注册监听;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
public class TestActivity extends AppCompatActivity {
private MyContentObserver myContentObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
myContentObserver = new MyContentObserver(null);
findViewById(R.id.button).setOnClickListener(v -> {
//获取某个系统属性的uri
Uri uri = Settings.Secure.getUriFor(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
//注册监听
getContentResolver().registerContentObserver(uri, true, myContentObserver);
});
}
@Override
protected void onDestroy() {
getContentResolver().unregisterContentObserver(myContentObserver);
myContentObserver = null;
super.onDestroy();
}
}
3、销毁页面时记得反注册;
getContentResolver().unregisterContentObserver(myContentObserver);