在 Android 中使用 BroadcastReceiver 检查网络连接
我正在使用 BroadcastReceiver 在我的应用程序运行时检查网络连接。我已将 BroadcastReceiver 与 Activity 绑定在一起,以便在连接中断时引入几个控件,例如 AlertDialog。但现在我不想将此接收器限制为特定活动,而是希望将其应用于我的整个应用程序(所有活动)。那么我应该采取什么方式来完成这项工作...
这是我使用的代码。请让我知道我的代码是否达到标准,如果有问题请纠正我。
package com.xx.mobile;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CheckforConnectivity extends Activity {
private static final String LOG_TAG = CheckforConnectivity.class.getSimpleName();
static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private boolean mActiveNetState = false;
private boolean mMobileNetState = false;
private boolean mStatus = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(ConnectivityCheckReceiver, filter);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(ConnectivityCheckReceiver);
}
private final BroadcastReceiver mConnectivityCheckReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
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);
Log.i(TAG, "Status : " + noConnectivity + ", Reason :" + reason + ", FailOver :" + isFailover + ", Current Network Info : " + currentNetworkInfo + ", OtherNetwork Info :" + otherNetworkInfo);
mStatus = noConnectivity;
Log.d(TAG, "Status :" + mStatus);
if(mStatus){
AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
builder.setMessage("Connection is not Available !");
builder.setTitle("Info");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
builder.setMessage("Connection is Available !");
builder.setTitle("Info");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
};
}
非常感谢任何形式的帮助。
谢谢
I am using the BroadcastReceiver to check the network connectivity while my app is running.I have binded the BroadcastReceiver with the Activity inorder to bring few controls like AlertDialog while the connectivity goes down. but now i don't want to restrict this receiver to a particular activity instead i want to make this to be applied for my whole app(All Activities). So what way should i have to proceed to get that done...
This is the code that i have used.Please let me know whether my code reaches the standard and please correct me if have gone somewhere wrong.
package com.xx.mobile;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CheckforConnectivity extends Activity {
private static final String LOG_TAG = CheckforConnectivity.class.getSimpleName();
static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private boolean mActiveNetState = false;
private boolean mMobileNetState = false;
private boolean mStatus = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION);
this.registerReceiver(ConnectivityCheckReceiver, filter);
}
@Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(ConnectivityCheckReceiver);
}
private final BroadcastReceiver mConnectivityCheckReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
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);
Log.i(TAG, "Status : " + noConnectivity + ", Reason :" + reason + ", FailOver :" + isFailover + ", Current Network Info : " + currentNetworkInfo + ", OtherNetwork Info :" + otherNetworkInfo);
mStatus = noConnectivity;
Log.d(TAG, "Status :" + mStatus);
if(mStatus){
AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
builder.setMessage("Connection is not Available !");
builder.setTitle("Info");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
builder.setMessage("Connection is Available !");
builder.setTitle("Info");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
};
}
Any sort of help is highly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你有两个选择。
第一个选项
首先,您应该不使用代码注册接收器,而是在 清单文件。通过这种方式,它会自动为您的应用程序注册。在接收器中,您必须将网络的当前状态存储在自定义的 集中的某个地方Application 类或单例类。
实现某种观察者模式,以便您的活动可以将自己注册到您的自定义应用程序类,该类包含网络状态。然后,Application 类通知每个注册的活动有关网络状态的更改。
您的活动类在 onCreate() 和 onDestroy() 中向 Application 类注册和取消注册(最好是 onResume() 和 onPause()),因此它们仅在网络更改可见时才收到有关网络更改的通知。
第二个选项
另一种选择是坚持当前代码并将广播接收器的引用集中保存在某个地方,同样,自定义应用程序类可以完成这项工作。
因此您的活动知道在哪里可以找到用于注册和取消注册的接收者。但请注意,您必须找到启动接收器的地方。另请记住,您必须处理应用程序可能因内存不足而被 Android 关闭并稍后重新启动的情况,然后您必须重新创建接收器。
I think you got 2 options.
First option
First you should register your receiver not with code but within the manifest file. By this way it is registered automatically for your application. Within you receiver you have to store the current state of the network somewhere centrally perhaps in a custom Application class or a singleton class.
Implement some kind of observer pattern so that your activities could register themselves to your custom Application class which holds the network state. The Application class then informs every registered activity about the change of the network state.
You activity class register and unregister to/from the Application class in onCreate() and onDestroy() (better would be onResume() and onPause()) so they get only informed about network changes when they're visible.
Second option
Another option would be to stick to you current code and hold the reference of the Broadcast receiver somewhere centrally, again a custom Application class would do the job.
So your activities know where to find the receiver for registering and unregistering. But be aware that you have to find a place where you initiate the receiver. Also keep in mind that you have to handle the case where you application might be closed by Android because of low memory and restarted later, you'll then have to recreate your receiver.
Flo 的选项一对于通过包含在清单文件中使广播接收器全局化是正确的。还有另一种选择是,将一个活动作为基本活动,并以此扩展您的所有活动,并在基本活动中注册您的接收器。
Flo's option one is correct for making Broadcast Receiver global by including in manifest file. there is another option is, make a activity as base activity and extends all your activity with this and register you receiver in base activity.