學習 Android Programming 的過程,是很順利的,也很享受的…
我甚至覺得,竟然簡單如此…裝個 Eclipse,下載個 sdk,跟著 Android 的網一步一步做…
http://developer.android.com/sdk/index.html
我的首個 Android Program,只是一個 qiye008 的客戶端,用來發一下短信…
(敏感內容黑掉,代碼只作參考,不含 layout.xml)
package com.qiye008.smstest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//((Button)findViewById(R.id.buttonSubmit)).setOnClickListener(submitButtonListener);
editTextDstNumber = (EditText)findViewById(R.id.autoCompleteTextViewDstNumber);
editTextContent = (EditText)findViewById(R.id.editTextContent);
}
//private OnClickListener submitButtonListener = new OnClickListener() {
public void submitClicked(View v) {
String dstNum = editTextDstNumber.getText().toString();
String content = editTextContent.getText().toString();
toastShow(smsSubmit(dstNum, content));
}
//};
private void toastShow(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
public String smsSubmit(String dst, String text) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://X.XXXXXX.com.cn/~idler/wxsmsgw/sms.php");
String content = "Error";
try {
// Add your data
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("dstnums", dst));
nameValuePairs.add(new BasicNameValuePair("text", text));
nameValuePairs.add(new BasicNameValuePair("key", "a724ad94-XXXX-XXXX-b7b4-643d2XXXXbef"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
content = EntityUtils.toString(entity);
//EntityUtils.consume(entity);
}
httpclient.getConnectionManager().shutdown();
} catch (ParseException e) {
toastShow(e.toString());
} catch (IOException e) {
toastShow(e.toString());
}
return content;
}
private EditText editTextDstNumber;
private EditText editTextContent;
}