我想编写一个 Android 应用程序,它将从互联网上检索数据并保存在本地文件中。这是我写的:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Runnable r = new Runnable() {
@Override
public void run() {
updateData();
}
};
Handler h = new Handler();
h.post(r);
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnectedOrConnecting()) {
return true;
}
else {
return false;
}
}
private void updateData() {
if(!isOnline()) {
Toast.makeText(this, "Unable to update data: Internet Connection Unavailable", Toast.LENGTH_SHORT).show();
}
else {
try {
HttpClient client = new DefaultHttpClient();
HttpGet req = new HttpGet("***SOME URL****");
HttpResponse res = client.execute(req);
InputStream is = res.getEntity().getContent();
InputStreamReader ir = new InputStreamReader(is);
StringBuilder sb = new StringBuilder();
Boolean end = false;
do {
int t = ir.read();
if(t==-1) {
end = true;
}
else {
sb.append((char)t);
}
}
while(!end);
String s = sb.toString();
File f = new File(getFilesDir(), "data.txt");
FileWriter fw = new FileWriter(f);
fw.write(s);
fw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
我让主线程阻塞了大约 2-3 秒。而且我不确定这是否是正确的方法。因此,如果您认为这是不正确的做法,请随时告诉我。
问候,萨伦