对于应用程序和服务器之间的连接,您需要创建 api 类,
public class PostParseGet {
public Context mActivity;
public boolean isNetError = false;
public boolean isConnectionTimeError = false;
public boolean isOtherError = false;
public boolean isDataError = false;
Object mFillObject;
// List<PropertyInfo> mPropertyInfo;
//
// CommonHelper mCommonHelper;
//
// SoapObject mSoapObjectRequest;
HashMap<String, String> mHashMap;
Gson mGson;
public PostParseGet(Context context) {
mActivity = context;
mGson = new Gson();
// mCommonHelper= new CommonHelper(mActivity);
}
public boolean check_Internet(Context mContext){
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;
mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
return true;
else
return false;
}
public static boolean isInternetOncheck(Context context) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (!(connec.getActiveNetworkInfo() != null && connec.getActiveNetworkInfo().isAvailable() && connec.getActiveNetworkInfo().isConnected())) {
// AppLog.logString(TAG+"Internet not avialable");
return false;
} else {
// AppLog.logString(TAG+"Internet available");
return true;
}
}
public Object httpPostData(String method,Object mObject,List<NameValuePair> postParameters,String json,String AddArrayName){
BufferedReader in = null;
isOtherError = false;
isConnectionTimeError = false;
mFillObject= null;
if(check_Internet(mActivity)){
isNetError = false;
isDataError=false;
try {
mFillObject = mObject.getClass().newInstance();
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 30*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
// String url = TagValues.SCU_URL+method;
String url = method;
HttpPost request = new HttpPost(url);
System.out.println("-----url "+url);
if(json!=null && !json.equalsIgnoreCase("")){
StringEntity params =new StringEntity(json.toString(), "UTF-8");
params.setContentType("application/json");
request.setEntity(params);
System.out.println("-----parameters "+json);
}else{
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
System.out.println("-----parameters "+postParameters.toString());
}
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
// in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
String result="";
try {
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if(result!=null)
if(!AddArrayName.equalsIgnoreCase("")){
result = "{"+AddArrayName+":"+result+"}";
}
// Log.i("Appname", "Response: \n" + result);
System.out.println("------- Final data: "+result);
mFillObject = mGson.fromJson(result, mFillObject.getClass());
}catch (Exception e) {
e.printStackTrace();
isOtherError = true;
}
}else{
isNetError = true;
}
return mFillObject;
}
}
创建解析器类后,您需要为后台进程创建异步任务,以便从 Web 服务器推送和获取数据,如下所示,
public class ThreadAsyncTask extends AsyncTask<String, Void, Object> {
private String TAG = "Async: ";
private Dialog mAlert_Dialog;
private String method;
private Context con;
private String json;
private Object mObject;
private OnTaskCompleted listener;
private PostParseGet mPostParseGet;
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
private String AddArrayname;
public interface OnTaskCompleted{
void onTaskCompleted(String method, Object result);
}
public ThreadAsyncTask(){
}
/**
*
* @param listener
* @param con
* @param json
* @param method
*/
public ThreadAsyncTask(OnTaskCompleted listener,Context con,Object object, String json, String method,List<NameValuePair> postParameters,String AddArrayName) {
// TODO Auto-generated constructor stub
this.listener = listener;
this.con = con;
this.json = json;
this.method = method;
this.mObject = object;
this.postParameters = postParameters;
this.AddArrayname = AddArrayName;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mAlert_Dialog = new Dialog(con);
mAlert_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mAlert_Dialog.setContentView(R.layout.dailog_progressbar);
mAlert_Dialog.setCancelable(false);
mAlert_Dialog.show();
}
@Override
protected Object doInBackground(String... urls) {
// Parcelable mParcelable;
for (String url : urls) {
if (isCancelled()) {
break;
}
mPostParseGet = new PostParseGet(con);
mObject = mPostParseGet.httpPostData(method,mObject,postParameters,json,AddArrayname);
// Utility ul=new Utility();
// result = (ul.setDataFromWebServiceSOAP(con,method, json));
}
return mObject;
}
@Override
protected void onPostExecute(Object result) {
mAlert_Dialog.dismiss();
if (listener != null)
listener.onTaskCompleted(method,result);
}
}
最后你需要在你的活动类中定义并启动网络服务......
mTextViewLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// postParameters.add(new BasicNameValuePair("username",mEditTextUsername.getText().toString()));
// postParameters.add(new BasicNameValuePair("password",mEditTextPassword.getText().toString()));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", mEditTextUsername.getText().toString());
jsonObject.put("password", mEditTextPassword.getText().toString());
}catch (JSONException e1) {
e1.printStackTrace();
}
if(PostParseGet.isInternetOncheck(LoginActivity.this)){
GetCommentList(TagValues.LOGIN_URL,jsonObject.toString(),postParameters);
}else{
CustomeDialog.dispDialog(LoginActivity.this, "Internet not available");
}
}
});
public void GetCommentList(String methodName,String json,List<NameValuePair> postParameters){
try {
mParcelableClass= new ParcelableClass();
ThreadAsyncTask testImple=new ThreadAsyncTask(listener, LoginActivity.this,mParcelableClass,json,methodName,postParameters,"");
testImple.execute("");
}catch (NullPointerException e) {}
}
private OnTaskCompleted listener = new OnTaskCompleted(){
@Override
public void onTaskCompleted(String methodName,Object result){
if(result!=null){
mParcelableClass= (ParcelableClass)result;
if(mParcelableClass!=null && mParcelableClass.getStatus()!=null && mParcelableClass.getStatus().equalsIgnoreCase("success")){
try {
Intent mIntent = new Intent(LoginActivity.this,YourSecondActivity.class);
startActivity(mIntent);
overridePendingTransition(R.anim.right_left, R.anim.right_left2);
}catch (NullPointerException e){
e.printStackTrace();
dispDialog(LoginActivity.this, "Invalid responce\n"+ e.toString());
return;
}catch (Exception e) {
e.printStackTrace();
dispDialog(LoginActivity.this, "Invalid responce\n"+ e.toString());
return;
}
}else{
dispDialog(LoginActivity.this, "Invalid Credential");
}
}
}
};
进度对话框 xml 看起来像
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backrepeat"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="@dimen/margin_5"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/margin_10" >
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminate="true" />
<TextView
android:id="@+id/txtMessage_progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_10"
android:gravity="center"
android:padding="@dimen/margin_10"
android:text="Please wait..."
android:textColor="@color/textColor"
android:textSize="@dimen/textsize_10sp"
android:textStyle="bold" />
</LinearLayout>
警报对话框创建者
public static void dispDialog(Activity ac,String dialogMsg){
final Activity activity=ac;
final Dialog Alert_Dialog = new Dialog(ac);
Alert_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Alert_Dialog.setContentView(R.layout.dailog_error);
((TextView)Alert_Dialog.findViewById(R.id.txtMessage)).setText(""+dialogMsg);
Alert_Dialog.setCancelable(false);
Alert_Dialog.show();
((Button) Alert_Dialog.findViewById(R.id.ok)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Alert_Dialog.cancel();
activity.finish();
activity.overridePendingTransition(R.anim.left_right, R.anim.left_right2);
}
});
parcelabel 类也定义为
public class ParcelabelClass implements Parcelable{
private List<GradeDataList> GradeList;
public List<GradeDataList> getGradeList() {
return GradeList;
}
public void setGradeList(List<GradeDataList> listData) {
GradeList = listData;
}
public GradeList(){
GradeList = new ArrayList<GradeDataList>();
// AutoCompleteIdName = new ArrayList<VoucherDataList>();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeTypedList(GradeList);
// arg0.writeTypedList(AutoCompleteIdName);
}
public static Parcelable.Creator<GradeList> CREATOR= new Creator<GradeList>() {
@Override
public GradeList[] newArray(final int size) {
return new GradeList[size];
}
@Override
public GradeList createFromParcel(final Parcel source) {
return new GradeList(source);
}
};
public GradeList(final Parcel in){
in.readTypedList(GradeList, GradeDataList.CREATOR);
}
public static class GradeDataList implements Parcelable{
private String id = "";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public GradeDataList(){
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
}
public static Parcelable.Creator<GradeDataList> CREATOR = new Creator<GradeDataList>() {
@Override
public GradeDataList[] newArray(final int size) {
return new GradeDataList[size];
}
@Override
public GradeDataList createFromParcel(final Parcel source) {
return new GradeDataList(source);
}
};
public GradeDataList(final Parcel in){
id= in.readString();
}
}
}