问题
Is there any background task which runs with in application to check for internet connectivity for below scenarios as common ?
1.Start of parsing/fetching data from server
2.In between of parsing/fetching from server
Any sample code or links helps me a lot.
回答1:
You can start an IntentService
or Service
and use this:
public boolean CheckInternet()
{
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.
if (wifi.isConnected()) {
return true;
} else if (mobile.isConnected()) {
return true;
}
return false;
}
Also don't forget to add this permission to the AndroidManifest
file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
回答2:
You can use a service for both the tasks.
for the first one, invoke the service, when the downloading is going to start.
Use a thread in the service that is executed after a while that checks for the active internet connection.
Edit-
It could be something like,
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
Toast.makeText(getBaseContext(), "Running Thread...", Toast.LENGTH_LONG).show();
// Check internet connectivity here
}
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
};
thread.start();
Have a look at this post also.
Also I have found two other options,
Have a look at Timer Task and Alarm Manager also to check internet connection after a while.
回答3:
You can use the below utility class make sure to give internet permission in manifest.
Let me know if any issues.
private static NetworkUtil mInstance;
private volatile boolean mIsOnline;
private NetworkUtil() {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
boolean reachable = false;
try {
Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = process.waitFor();
reachable = (returnVal==0);
} catch (Exception e) {
e.printStackTrace();
}
mIsOnline = reachable;
}
}, 0, 5, TimeUnit.SECONDS);
}
public static NetworkUtil getInstance() {
if (mInstance == null) {
synchronized (NetworkUtil.class) {
if (mInstance == null) {
mInstance = new NetworkUtil();
}
}
}
return mInstance;
}
public boolean isOnline() {
return mIsOnline;
}
来源:https://stackoverflow.com/questions/14358952/checking-internet-connection-in-android