在 Android 中使用 BroadcastReceiver 检查网络连接 [英] Checking the Networking Connectivity using BroadcastReceiver in Android

查看:22
本文介绍了在 Android 中使用 BroadcastReceiver 检查网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BroadcastReceiver 在我的应用程序运行时检查网络连接.我已将 BroadcastReceiver 与 Activity 绑定,以便在连接中断时带来一些控件,如 AlertDialog.但现在我不想将此接收器限制为特定活动,而是希望将其应用于我的整个应用程序(所有活动).那么我应该怎么做才能完成...

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.

谢谢

推荐答案

我想你有 2 个选择.

I think you got 2 options.

第一个选项

首先,您不应该使用代码而是在 manifest 文件中注册您的接收器.通过这种方式,它会自动为您的应用程序注册.在您的接收器中,您必须将网络的当前状态集中存储在一个自定义的应用程序 类或单例类.

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.

实施某种观察者模式,以便您的活动可以将自己注册到您的自定义应用程序类保存网络状态.Application 类然后通知每个注册的活动关于网络状态的变化.

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.

您的活动类在 onCreate() 和 onDestroy()(最好是 onResume() 和 onPause())中向 Application 类注册和注销,因此它们仅在可见时获知网络更改.

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.

第二种选择

另一种选择是坚持您当前的代码并将广播接收器的引用集中在某个地方,再次自定义应用程序类将完成这项工作.

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.

因此您的活动知道在哪里可以找到接收器以进行注册和取消注册.但请注意,您必须找到一个可以启动接收器的地方.另请记住,您必须处理应用程序可能因内存不足而被 Android 关闭并稍后重新启动的情况,然后您必须重新创建接收器.

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.

这篇关于在 Android 中使用 BroadcastReceiver 检查网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆