我的应用程序主要是基于互联网的,当设备没有上网时,它只是崩溃,因为它试图下载文件但没有成功。我也刚刚在输入时意识到如果它需要的数据离线它也会崩溃。我已经尝试阅读文档并尝试将其添加到我的应用程序,但似乎我需要的东西与我一直在阅读的东西不同。
我使用我的MainActivity来加载片段,所以我怀疑我可以在其中放置某种代码来显示片段使用区域的对话框。无论哪种方式,我都会添加我的MainActivity和我的互联网加载片段。
MainActivity.class:
public class MainActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabSwipe mTabSwipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new FirstLaunchEULA(this).show();
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
mViewPager.setOffscreenPageLimit(2);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabSwipe = new TabSwipe(this, mViewPager);
mTabSwipe.addTab(bar.newTab().setText("Games"), A_Internet_Service.class, null);
mTabSwipe.addTab(bar.newTab().setText("Movies"), Test_Fragment.class, null);
mTabSwipe.addTab(bar.newTab().setText("Tech"), Purchase_Fragment.class, null);
}
}
A_Internet_Service.class:
public class A_Fragment_Service extends Fragment {
// All static variables
static final String URL = "this.is.a.url";
// XML node keys
static final String KEY_DATA = "data"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE1 = "date1";
static final String KEY_DATE2 = "date2";
static final String KEY_DATE3 = "date3";
static final String KEY_DATE2VIS = "date2vis";
static final String KEY_DATE3VIS = "date3vis";
static final String KEY_PLATFORMS = "platforms";
static final String KEY_THUMB_URL = "thumb_url";
ArrayList<HashMap<String, String>> songsList;
View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new TheTask().execute();
/*
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}); */
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.main, container, false);
//list = (ListView) view.findViewById(R.id.data_list);
return view;
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
class TheTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
songsList = new ArrayList<HashMap<String, String>>();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_DATA);
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DATE1, parser.getValue(e, KEY_DATE1));
map.put(KEY_DATE2, parser.getValue(e, KEY_DATE2));
map.put(KEY_DATE3, parser.getValue(e, KEY_DATE3));
map.put(KEY_DATE2VIS, parser.getValue(e, KEY_DATE2VIS));
map.put(KEY_DATE3VIS, parser.getValue(e, KEY_DATE3VIS));
map.put(KEY_PLATFORMS, parser.getValue(e, KEY_PLATFORMS));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Getting adapter by passing xml data ArrayList
LazyAdapter adapter = new LazyAdapter(getActivity(), dataList);
view = getView();
ListView mlist = (ListView) view.findViewById(R.id.data_list);
mlist.setAdapter(adapter);
super.onPostExecute(result);
}
}
}
Edited Fragment部分:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.main, container, false);
return view;
if(!isConnected(getActivity())) buildDialog(getActivity()).show();
else {
new TheTask().execute();
}
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet connection.");
builder.setMessage("You have no internet connection");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
//All the other code
答案 0 :(得分:11)
例如,您可以检查您的互联网连接:
如果设备具有Internet连接或即将连接Internet,则返回true。
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
else return false;
} else
return false;
}
这就是您在应用程序中使用它的方式: (例如,在片段onCreateView中,如果设备未连接,则显示对话框,请参阅以下有关如何生成简单对话框的代码)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.yourlayout, container, false);
// getActivity() will hand over the context to the method
// if you call this inside an activity, simply replace getActivity() by "this"
if(!isConnected(getActivity())) buildDialog(getActivity()).show();
else {
// we have internet connection, so it is save to connect to the internet here
new TheTask().execute();
}
// do other stuff
return view;
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting())) return true;
else return false;
} else return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet connection.");
builder.setMessage("You have no internet connection");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
这可以在您的代码中的任何位置进行,例如在您的Activity的onCreate()方法中,或在Fragment的onCreateView()方法中 - 无论您希望连接到互联网的哪个位置,首先检查 - 然后做互联网的东西。
不要忘记权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我希望这会有所帮助;)
答案 1 :(得分:0)
我给你一个network-util,也许永远帮助你。
public final class NetworkUtils {
public static final byte CONNECTION_OFFLINE = 1;
public static final byte CONNECTION_WIFI = 2;
public static final byte CONNECTION_ROAMING = 3;
public static final byte CONNECTION_SLOW = 4;
public static final byte CONNECTION_FAST = 5;
private static String sUserId;
private NetworkUtils() {}
/**
* Check if the device is connected to the internet (mobile network or
* WIFI).
*/
public static boolean isOnline(Context _context) {
boolean online = false;
TelephonyManager tmanager = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
if (tmanager != null) {
if (tmanager.getDataState() == TelephonyManager.DATA_CONNECTED) {
// Mobile network
online = true;
} else {
// WIFI
ConnectivityManager cmanager = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cmanager != null) {
NetworkInfo info = cmanager.getActiveNetworkInfo();
if (info != null)
online = info.isConnected();
}
}
}
return online;
}
/**
* Get the User Agent String in the format
* AppName + AppVersion + Model + ReleaseVersion + Locale
*/
public static String getUserAgentString(Context _c, String _appName) {
if(_appName == null)
_appName = "";
String agent = _appName + " " + BackendUtil.getAppVersionString(_c) + " (" + Build.MODEL + "; Android "
+ Build.VERSION.RELEASE + "; " + Locale.getDefault() + ")";
if(agent.startsWith(" "))
agent = agent.substring(1);
return agent;
}
/**
* Evaluate the current network connection and return the
* corresponding type, e.g. CONNECTION_WIFI.
*/
public static byte getCurrentNetworkType(Context _context){
NetworkInfo netInfo = ((ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if(netInfo == null)
return CONNECTION_OFFLINE;
if(netInfo.getType() == ConnectivityManager.TYPE_WIFI)
return CONNECTION_WIFI;
if(netInfo.isRoaming())
return CONNECTION_ROAMING;
if(!(netInfo.getType() == ConnectivityManager.TYPE_MOBILE
&& (netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS
|| netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
|| netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSUPA
|| netInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSPA
|| netInfo.getSubtype() == 13 // NETWORK_TYPE_LTE
|| netInfo.getSubtype() == 15))) // NETWORK_TYPE_HSPAP
{
return CONNECTION_SLOW;
}
return CONNECTION_FAST;
}
/**
* Return the current IP adresse of the device or null if it could not be
* found.
*/
public static String getIpAdress() {
String result = null;
try {
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
NetworkInterface iface = interfaces.nextElement();
for (Enumeration<InetAddress> adresses = iface.getInetAddresses(); adresses.hasMoreElements();) {
InetAddress ip = adresses.nextElement();
if (!ip.isLoopbackAddress())
result = ip.getHostAddress();
}
}
} catch (SocketException _e) {
LL.error("Could not find device's ip adress");
}
return result;
}
/**
* Return a MD5 hash of the device id.
*/
public static synchronized String getUserId(Context _context) {
if (sUserId == null) {
TelephonyManager tm = (TelephonyManager) _context.getSystemService(Context.TELEPHONY_SERVICE);
String id = tm.getDeviceId();
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(id.getBytes());
byte[] digest = digester.digest();
// Convert to hex string
BigInteger converter = new BigInteger(1, digest);
String md5 = converter.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
sUserId = md5;
} catch (NoSuchAlgorithmException _e) {
LL.error("Could not find MD5");
}
}
return sUserId;
}
}