使用 BroadcastReceiver 拦截 android.settings.SETTINGS

Intercept android.settings.SETTINGS with BroadcastReceiver

早上好,我正在尝试拦截“设置”activity 开头。 基本上当用户尝试访问全局设置时 activity 我想触发一些事件。

我正在使用 BroadcastReceiver,代码如下:

public class MainActivity extends Activity {

IntentFilter intentFilter;
BroadcastReceiver receiver;
Button settings;

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

    intentFilter = new IntentFilter(Settings.ACTION_SETTINGS);

    ((Button)findViewById(R.id.settings)).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            Log.v("MYAPP", "starting intent");
        }
    });

}

@Override
protected void onPause() {
    super.onPause();

    unregisterReceiver(receiver);
    Log.v("MYAPP", "on pause, unregister receiver");
}

@Override
protected void onResume() {
    super.onResume();

    receiver = new MyBroadcastReceiver();
    registerReceiver(receiver, intentFilter);
    Log.v("MYAPP", "on resume, register receiver");
}

private class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("MYAPP", "received settings intent");
    }
}

}

但是接收器没有拦截任何意图...

我错过了什么?

感谢您的宝贵时间

What am I missing?

您不能 "intercept" startActivity() 使用 BroadcastReceiver 调用。 BroadcastReceiver 接收广播,而不是 startActivity() 呼叫。

经过反馈,我找到了另一种拦截设置打开的方法:

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    Log.v(TAG, "Focus changed !");

    if (!hasFocus) {
        Log.v(TAG, "Lost focus !");
        ActivityManager am = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn != null
                && cn.getClassName().equals(
                        "com.android.settings.Settings")) {
            Log.v(TAG, "settings intercepted");

            // do your stuff

        }
    }
}