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

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

问题描述

我是用的BroadcastReceiver来检查网络连接,而我的应用程序是running.I已经绑定了的BroadcastReceiver的活动序带来一些控件,如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...

这是在code,我有used.Please让我知道我的code是否达到标准,请纠正我,如果已经在某处错误的。

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();
    }



    }
};
}

帮助任何种类是非常AP preciated。

Any sort of help is highly appreciated.

感谢

推荐答案

我觉得你有2个选择。

首选项

首先,你应该注册您的接收器无法与code,但在清单文件。通过这种方式,为您的应用程序会自动注册。在您接收器,你必须集中的地方可能存储在自定义应用程序网络的当前状态类或单例类。

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.

您活动类注册和取消注册到/从的onCreate()和的onDestroy()(更好的是onResume(),并在onPause()),所以应用程序类,他们只得到通知时,他们看到有关网络的变化。

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.

第二个选项

另一种选择是坚持你目前的code和持有广播接收器的参考某处集中,又一个自定义的应用程序类将完成这项工作。

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.

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

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