import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*; //加入widget類別
import android.view.*; //加入view類別
public class MainActivity extends ActionBarActivity {
//宣告一個執行緒
Thread myThread;
TextView t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView)findViewById(R.id.textView1);
//產生新的執行緒並且啟動執行緒
myThread = new myThread();
myThread.start();
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//因為Android 4.X已無法由其他的執行緒來更改主執行緒的UI設定,
//所以必須以Handler來更改主執行緒的UI設定
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
//只能以Handle來更改textView的值
t1.setText(msg.getData().toString());
}
};
//新的執行緒
class myThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
//Bundle可以在多個執行緒中互相傳遞訊息
Bundle myBundle = new Bundle();
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://192.168.1.10/test.php");
HttpGet request = new HttpGet();
request.setURI(website);
//PHP網頁回傳的資料
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
//將Response資料的前100個字以字串的類型代入Bundle
myBundle.putString("aaa",EntityUtils.toString(resEntity).substring(1,100));
}
else{
myBundle.putString("bbb","Nothing");
}
//以Message資料類型(不能單純以String來傳遞)傳遞資料並呼叫Handler(就是上面自訂的mHandler函數來執行更改ui的值)
Message msg = new Message();
msg.setData(myBundle);
mHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}