我在Activity中创建了一个自定义接收器,当互联网连接时自动调用Web服务。它工作正常但我在下面的场景中遇到了问题。
那个时候没有调用OnReceive函数。
下面的代码
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
bar.setVisibility(View.VISIBLE);
callAuthorizeWebservice();
} else {
bar.setVisibility(View.INVISIBLE);
Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
}
}
};
和
@Override
protected void onStart() {
super.onStart();
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
请帮我解决这个问题
答案 0 :(得分:0)
看起来你不是registering
以BroadcastReceiver
编程的。{/ p>
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.BOOT_COMPLETED");
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(mConnReceiver , filter);
以编程方式创建的接收器需要以编程方式注册。如果您以编程方式创建并在AndroidManifest
中输入条目,则不会被触发。
希望这有帮助。
答案 1 :(得分:0)
在清单中添加以下权限以接收Boot completed事件。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
在AndroidManifest.xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
现在定义MyBroadcastReceiver
-
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
bar.setVisibility(View.VISIBLE);
callAuthorizeWebservice();
} else {
bar.setVisibility(View.INVISIBLE);
Toast.makeText(SplashScreenActivity.this, "Check Your Internet connection", Toast.LENGTH_LONG).show();
}
}
}