8

谁能告诉我一种创建应用程序内广播接收器的方法?我已经创建了可以发送消息的 BroadcastReceiver。即使应用程序处于后台状态它也可以工作,我希望它仅在应用程序处于前台时工作。

  public class MainActivity extends Activity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                this.registerReceiver(this.mConnReceiver, new IntentFilter(
                        ConnectivityManager.CONNECTIVITY_ACTION));
            }

            private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {

                public void onReceive(Context context, Intent intent) {
                    boolean noConnectivity = intent.getBooleanExtra(
                            ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                    String reason = intent
                            .getStringExtra(ConnectivityManager.EXTRA_REASON);
                    boolean isFailover = intent.getBooleanExtra(
                            ConnectivityManager.EXTRA_IS_FAILOVER, false);

                    NetworkInfo currentNetworkInfo = (NetworkInfo) intent
                            .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                    NetworkInfo otherNetworkInfo = (NetworkInfo) intent
                            .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

                    if (currentNetworkInfo.isConnected()) {
                        System.out.println("Connected");
                        Toast.makeText(getApplicationContext(), "Connected",
                                Toast.LENGTH_LONG).show();
                    } else {
                        System.out.println("Not Connected");
                        Toast.makeText(getApplicationContext(), "Not Connected",
                                Toast.LENGTH_LONG).show();
                    }
                }
            };

        }

So here is my code which is checking network state and generating a BroadcastReceiver. I haven't added anything in manifest.
4

2 回答 2

2

有很多方法可以做到这一点。我能想到的前两个是这样的:

  1. 如果您<receiver>在清单中用 声明<intent-filter>,您可以在应用程序中启用和禁用它,以便仅在应用程序处于前台时启用它。为此,最初通过添加android:enabled="false"到清单条目来禁用接收器<receiver>。现在,当您的应用程序运行时,onResume()您想要启用接收器。用于PackageManager.setComponentEnabledSetting()执行此操作。当您的活动进入后台时,onPause()您可以再次禁用接收器。

  2. 动态注册和注销接收器。为此,您无需在清单中声明接收者。在您的应用程序中,使用适当的意图过滤器创建您的BroadcastReceiveronResume()调用的实例。registerReceiver()当应用程序进入后台时,onPause()调用unregisterReceiver()将其删除。接收者只会onReceive()在应用程序处于前台时接收调用。

于 2013-09-11T09:06:13.833 回答
1

见 Context.registerReceiver() 和 Context.unregisterReceiver()

于 2013-09-11T08:58:04.040 回答