这肯定会奏效。在 4.0 android 版本中,我们必须创建 asynctask 以避免异常,即NetworkOnMainThreadException
会得到。它对我来说工作正常。
public class Http_Get_JsonActivity extends Activity implements OnClickListener {
String d = new Date().toString();
private static final String TAG = "MyPost";
private boolean post_is_running = false;
private doSomethingDelayed doSth;
private String url = "http://192.168.1.1";
private InputStream is;
private String json;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pushButton = (Button) findViewById(R.id.button1);
pushButton.setOnClickListener(this);
}
@Override
protected void onPause() {
super.onPause();
if (post_is_running) { // stop async task if it's running if app gets
// paused
Log.v(TAG, "Stopping Async Task onPause");
doSth.cancel(true);
}
}
@Override
protected void onResume() {
super.onResume();
if (post_is_running) {
// start async task if it was running previously and was stopped by
// onPause()
Log.v(TAG, "Starting Async Task onResume");
doSth = (doSomethingDelayed) new doSomethingDelayed().execute();
// ((Button) findViewById(R.id.push_button)).setText("Resuming..");
}
}
public void onClick(View v) {
if (post_is_running == false) {
post_is_running = true;
Log.v(TAG, "Starting Async Task onClick");
doSth = (doSomethingDelayed) new doSomethingDelayed().execute();
// ((Button) findViewById(R.id.push_button)).setText("Starting..");
} else {
Log.v(TAG, "Stopping Async Task onClick");
post_is_running = false;
doSth.cancel(true);
// ((Button) findViewById(R.id.push_button)).setText("Stopping..");
}
}
private class doSomethingDelayed extends AsyncTask<Void, Integer, Void> {
private int num_runs = 0;
@Override
protected Void doInBackground(Void... gurk) {
// while (!this.isCancelled()) {
Log.v(TAG, "going into postData");
long ms_before = SystemClock.uptimeMillis();
Log.v(TAG, "Time Now is " + ms_before);
postData();
Log.v(TAG, "coming out of postData");
publishProgress(num_runs);
return null;
}
@Override
protected void onCancelled() {
Context context = getApplicationContext();
CharSequence text = "Cancelled BG-Thread";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, text, duration).show();
}
@Override
protected void onProgressUpdate(Integer... num_runs) {
Context context = getApplicationContext();
}
}
/**
* Method to send data to the server
*/
public void postData() {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
System.out.println("--httppost----" + httpPost);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("--httpResponse----" + httpResponse);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("--httpEntity----" + httpEntity);
is = httpEntity.getContent();
System.out.println("--is----" + is);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
JSONArray jObj = new JSONArray(json);
System.out.println("--jObjt--" + jObj);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
请享用..