我正在Android中练习,我想显示ping的值。我按照现有的答案(this topic)。事实是,这个人提供的代码并没有显示任何信息(我为了测试函数的返回值而烦恼它#34; ping")。我这样称呼函数:
Toast.makeText(getApplicationContext(), ping("http://www.stackoverflow.com"), Toast.LENGTH_SHORT).show();
任何其他类型的代码只是显示ping值?
我确定我的代码没有任何其他进程,我只想最终在一个小的textView中显示这个结果。
这是我的代码。
MainActivity.java
private String ping(String url) {
String str = "";
try {
Process process = Runtime.getRuntime().exec(
"/system/bin/ping -c 8 " + url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
int i;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
reader.close();
// body.append(output.toString()+"\n");
str = "ping : " + output.toString();
// Log.d(TAG, str);
} catch (IOException e) {
// body.append("Error\n");
e.printStackTrace();
}
return str;
}
private Button button;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), ping("http://www.stackoverflow.com"), Toast.LENGTH_SHORT).show();
});
}); }
答案 0 :(得分:0)
yourTextView.setText(ping("http://www.stackoverflow.com"));
答案 1 :(得分:0)
尝试类似这样的内容:Android- Unstable, slow, unreliable PING
public class NameOfYourActivity
// you need to define this value here, you will need it between "voids", "booleans", ...
long timeofping;
<强> OnCreate中:
// button on click listener
Button clickMyButton = (Button)findViewById(R.id.button);
clickFirstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// launch the ping process in a separate thread
// beacuse of the stability of the app
new Thread(ping).start();
}
});
方法“onCreate”后
// this code runs after the code bellow ("public Runnable ping ...")
void setPingResult(long pingtime) {
Toast.makeText(getApplicationContext(), timeofping + " milliseconds", Toast.LENGTH_LONG).show();
}
// thread of "ping" process
public Runnable ping = new Runnable() {
@Override
public void run() {
Runtime runtime = Runtime.getRuntime();
try {
long a = System.currentTimeMillis() % 1000;
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
ipProcess.waitFor();
timeofping = System.currentTimeMillis() % 1000 - a;
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
// update the ping result - we need to call this on the UI thread
// because it updates UI elements (TextView)
runOnUiThread(new Runnable() {
public void run() {
setPingResult(timeofping);
}
});
}
}
如果有任何错误,请修理我!
别忘了“进口”! (等import android.widget.Toast;
)
答案 2 :(得分:-1)
发现我的错误:需要使用8.8.4.4
之类的IP地址代替域地址行www.google.com
。可能需要DNS权限吗?