我刚刚创建了一个从网站获取数据的安卓应用,我想要检查设备是否连接到互联网。 如果设备有网络连接,则运行我的代码并获取数据并将其显示出来,否则,如果设备没有连接到互联网,则显示无互联网连接消息。 我尝试使用以下代码来检查互联网连接。当设备连接到互联网时,我该如何调用此代码?
我的Java代码:
我的Java代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
private Context context;
//check Internet connection.
private void checkInternetConnection(){
ConnectivityManager check = (ConnectivityManager) this.context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null)
{
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
@Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//some code
}
//parsing first URL
String [] resultArray=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
String [] resultArray1=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
try{
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
当连接打开时如何运行代码,并在应用没有互联网连接时如何显示消息?