我正在构建一个列表视图 android 应用程序。我希望在从数组中的列表中单击一个 url 时返回一条消息,告诉用户该站点是离线还是在线。我通过快速 ping 来执行此操作,它返回一个布尔值来说明这一点。我是一个 java 新手,我知道这与我调用 pinUrl() 方法的方式有关,因为当我从 onListItemClick() 中删除所说的 if 语句时,应用程序不会崩溃。
这是我的 MainActivity 供参考:
package com.seven.webtools;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
@SuppressLint("UseValueOf")
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
String[] Sites = res.getStringArray(R.array.Sites);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Sites));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Get the selected url
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String address = o.toString();
//Ping the address
String Status = "offline";
if (MainActivity.pingUrl(address) == true){
Status = "online";
}
//Return the result
Toast.makeText(this, address + " is " + Status, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static boolean pingUrl(final String address) {
try {
final URL url = new URL("http://" + address);
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
final long startTime = System.currentTimeMillis();
urlConn.connect();
final long endTime = System.currentTimeMillis();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("Time (ms) : " + (endTime - startTime));
System.out.println("Ping to "+address +" was success");
return true;
}
} catch (final MalformedURLException e1) {
e1.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
return false;
}
}
如果你能帮助我,非常感谢:)