Reputation: 11
I am making a weather widget. If I install the widget on the home screen, app configuration starts automatically. I'd like to prevent the configuration from running if there is no wifi or 3g. I used ConnectivityManager in the instance of AppWidgetProvider, but it didn't work. And I used ConnectivityManager in the java class of widget configuration, but it still didn't work with error messages "..stopped unexpectedly." Anyone who can help me?
Upvotes: 1
Views: 424
Reputation: 38335
You need to add network permissions to the Manifest to check network availability. And don't forget about the internet permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Here's a helper class to check network availability:
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkUtils
{
public static boolean isOnline(Service service)
{
ConnectivityManager mgr = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
return isOnline(mgr);
}
public static boolean isOnline(Context context)
{
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return isOnline(mgr);
}
private static boolean isOnline(ConnectivityManager mgr)
{
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
return true;
}
return false;
}
}
Upvotes: 1
Reputation: 1961
Did you add uses-permissions to your manifest file to access the network state? If not you should add them.
Upvotes: 2