有没有人能告诉我如何创建一个应用内的广播接收器?我已经创建了一个可以弹出消息的广播接收器。它甚至在应用程序处于后台状态时也能正常工作,但我希望它只在应用程序处于前台时才能工作。
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.
registerReceiver()
调用从onCreate()
移动到onResume()
,并在onPause()
中添加unregisterReceiver()
调用即可。 - David WasseronReceive()
中,您可以调用isInitialStickyBroadcast()
。如果返回true
,则可以忽略对onReceive()
的调用,因为这只是通知您当前的状态。 - David Wasser