我已经创建了一个Android应用程序,它使用Web服务发送和检索JSON数据。
当我在设备上线时发出请求它可以正常工作但当设备离线时应用程序卡住并打印出空指针异常错误。
有没有办法收听互联网连接?
答案 0 :(得分:1)
您可以通过此检查是否已连接到互联网。
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
答案 1 :(得分:1)
如果在请求/响应过程中连接丢失,您的问题和评论似乎就会出现问题。因此,为了监听此更改,您需要创建一个BroadcastReceiver(NetworkStateReceiver)以侦听网络状态更改,如下所示: NetworkStateReceiver.java
package your.package.name;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.ArrayList;
import java.util.List;
public class NetworkStateReceiver extends BroadcastReceiver {
// Listeners list
protected List<NetworkStateReceiverListener> listeners;
// Connection flag
protected Boolean connected;
/**
* Public constructor
*/
public NetworkStateReceiver() {
listeners = new ArrayList<NetworkStateReceiverListener>();
connected = null;
}
/**
*
* @param context Context - Application context
* @param intent Intent - Manages application actions on network state changes
*/
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null) return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if((ni != null) && ni.isConnected()) {
connected = true;
} else {
connected = false;
}
mNotifyStateToAll();
}
/**
* Notify the state to all needed methods
*/
private void mNotifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
mNotifyState(listener);
}
/**
* Notify the network state
* @param listener NetworkStateReceiverListener - receives network state change
*/
private void mNotifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null) return;
if(connected == true) {
listener.networkAvailable();
} else {
listener.networkUnavailable();
}
}
/**
* Add listener once it is needed
* @param l NetworkStateReceiverListener - receives network state change
*/
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
mNotifyState(l);
}
/**
* Remove the listener once it is not needed anymore
* @param l NetworkStateReceiverListener - receives network state change
*/
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
/**
* Set interface to communicate with Main methods
*/
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
您的活动需要实现此目的:
public class MyActivity extends Activity implements NetworkStateReceiver.NetworkStateReceiverListener {
// Receiver that detects network state changes
private NetworkStateReceiver networkStateReceiver;
private boolean mNetworkAvailable;
...
// What ever the code you want or need
...
/**
* Call back for NetworkStateReceiver to set the network state to available
*/
@Override
public void networkAvailable() {
Log.d(TAG, "I'm in, baby! Dance, dance revolution!");
sNetworkAvailable = true;
// Network available again do things here
}
/**
* Call back for NetworkStateReceiver to set the network state to unavailable
*/
@Override
public void networkUnavailable() {
Log.d(TAG, "I'm dancing with myself, noone can see me.");
sNetworkAvailable = false;
// Network broke, warn the user, or do alternative action
}
/**
* Need to register the receiver
*/
@Override
public void onResume() {
super.onResume();
// Register the network state receiver to listen to network state change
if (networkStateReceiver == null) {
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
}
/**
* Unregister the receiver as you do not need it anymore
*/
@Override
public void onDestroy() {
super.onDestroy();
// Remove network state receiver and listener as we don't need them at this point
if (networkStateReceiver != null) {
networkStateReceiver.removeListener(this);
this.unregisterReceiver(networkStateReceiver);
networkStateReceiver = null;
}
}
...
// What ever the code you want or need
...
}
答案 2 :(得分:0)
由(Seshu Vinay)
回答此方法检查移动设备是否已连接到互联网,如果已连接则返回true:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
清单中的,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
修改:此方法实际检查设备是否已连接到互联网(有可能它已连接到网络但未连接到互联网)。
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
答案 3 :(得分:0)
在您的清单添加权限
中 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Java
public boolean networkstatus() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
if(networkstatus())
{
// do your process
}
else
{
//alert message for no internet connection
}
答案 4 :(得分:0)
在请求之前,Web服务调用此方法
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NInfo = cm.getActiveNetworkInfo();
if (NInfo != null && NInfo.isConnectedOrConnecting())
return true;
else
return false;
}
if(isOnline()){
// request the service
// but make sure that U have surrounded the calling web-service by try and catch
try{
// here make your request when the connection go offline the app will catch the error and ignore the process
}catch (Exception e) {
}
添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />