当互联网连接关闭时,我的应用程序崩溃了

时间:2014-05-15 06:48:20

标签: android broadcastreceiver

在我的应用中,我检查互联网是否可用。我为此使用广播接收器。当我运行我的应用程序时,(当连接互联网时)它可以工作。但是,当我断开互联网连接时,它就会崩溃。怎么了。 这是我的代码: 我的活动:

public class BroadcastActivity extends ActionBarActivity {
  private static Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);
        Intent intent=new Intent(this, ConnectionReciever.class);
        sendBroadcast(intent);

    }


}

接收者类:

public class ConnectionReciever extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo=connectivityManager.getActiveNetworkInfo();
        if(activeNetInfo!=null & activeNetInfo.isConnected())
        {
            Toast.makeText(context, "Internet Connection is Active", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(context, "Internet Connection Timed Out! Please Try Again!!", Toast.LENGTH_LONG).show();
        }

    }

}

我还在清单中添加了权限,并在清单中注册了接收者。

Log cat:

    Failed to install Check_Network_Status.apk on device 'emulator-5554': adb rejected install command with: device offline
    [2014-05-15 12:09:48 - Check_Network_Status] com.android.ddmlib.AdbCommandRejectedException: device offline
    [2014-05-15 12:09:48 - Check_Network_Status] Launch canceled!

2 个答案:

答案 0 :(得分:0)

在接收器类中替换以下代码,你需要在if中检查另一个条件isAvailable()。

ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo=connectivityManager.getActiveNetworkInfo();
    if(activeNetInfo!=null && activeNetInfo.isAvailable() && activeNetInfo.isConnected())
    {
        Toast.makeText(context, "Internet Connection is Active", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connection Timed Out! Please Try Again!!", Toast.LENGTH_LONG).show();
    }

答案 1 :(得分:0)

退出eclipse,杀死adb并重启eclipse。 尝试adb kill-serveradb start-server重新启动adb。它可以在你的android sdk目录中的子文件夹工具中找到。