com.example.ridemepassenger.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.example.ridemepassenger.MainActivity.java

Source

package com.example.ridemepassenger;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import publicFunctions.PollRunnable;
import publicFunctions.static_saving;
import Data.Data;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

//?????import

public class MainActivity extends Activity {
    Vibrator mVibrator01;
    private static final int CODE_START = 0;
    private static final int CODE_END = 1;
    public static final String EXTRA_LOGGEDIN = "EXTRA_LOGGEDIN";
    private static boolean isFirstGetLocation = true;

    private String startGeo = ""; //?"{longitude: double, latitude: double}"
    private String startLocation = "";
    private String destination = "";
    private double longitude = 0;
    private double latitude = 0;

    private Dialog alertDialog;
    ProgressDialog dialog;
    private Button mSubmitButton;
    private EditText mStartEdit;
    private EditText mEndEdit;
    private Toast mToast;
    MapView mMapView = null;
    BaiduMap mBaiduMap = null;

    private Timer timer = new Timer();
    private TimerTask timerTask;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);

        mSubmitButton = (Button) findViewById(R.id.main_submit);
        mStartEdit = (EditText) findViewById(R.id.main_start_position);
        mEndEdit = (EditText) findViewById(R.id.main_end_position);

        mSubmitButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (longitude != 0 && latitude != 0 && !"".equals(mStartEdit.getText().toString())
                        && !"".equals(mEndEdit.getText().toString())) {
                    new sendto_sever().execute();
                } else {

                }
            }
        });

        mStartEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus) {
                    Intent i = new Intent(MainActivity.this, InputStartActivity.class);
                    startActivityForResult(i, CODE_START);
                }
            }
        });

        mEndEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus) {
                    Intent i = new Intent(MainActivity.this, InputDestActivity.class);
                    startActivityForResult(i, CODE_END);
                }
            }
        });

        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(19f));
        //  
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mLocationClient = new LocationClient(getApplicationContext()); //LocationClient
        //
        mVibrator01 = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
        initLocation();

        //      LatLng point = new LatLng(30.275354, 120.132376);
        //        BitmapDescriptor bitmap = BitmapDescriptorFactory  
        //             .fromResource(R.drawable.location_arrows);  
        //        OverlayOptions option = new MarkerOptions()  
        //       .position(point)  
        //       .icon(bitmap);  
        //      //Marker  
        //      mBaiduMap.addOverlay(option);

        //Maker??  
        //      LatLng point = new LatLng(39.963175, 116.400244);  
        //      LatLng point2 = new LatLng(38.963175, 115.400244);  
        //      //Marker  
        //      BitmapDescriptor bitmap = BitmapDescriptorFactory  
        //          .fromResource(R.drawable.dot_driver);  
        //      BitmapDescriptor bitmap2 = BitmapDescriptorFactory  
        //             .fromResource(R.drawable.dot_passenger);  
        //      BitmapDescriptor bitmap3 = BitmapDescriptorFactory  
        //             .fromResource(R.drawable.location_arrows);  
        //      //MarkerOptionMarker  

        //      OverlayOptions options = new MarkerOptions()
        //       .position(point)  //marker?
        //       .icon(bitmap)  //marker
        //       .zIndex(9)  //marker
        //       .draggable(true);  //
        //      //marker
        //      Marker marker = (Marker) (mBaiduMap.addOverlay(options));

        // markericons?period?
        //      ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
        //      giflist.add(bitmap);
        //      giflist.add(bitmap2);
        //      giflist.add(bitmap3);
        //      OverlayOptions ooD = new MarkerOptions().position(point2).icons(giflist)
        //                  .zIndex(0).period(10);   
        //      Marker mMarkerD = (Marker) (mBaiduMap.addOverlay(ooD));
        //      //BaiduMapsetOnMarkerDragListenermarker?
        //      mBaiduMap.setOnMarkerDragListener(new OnMarkerDragListener() {
        //          public void onMarkerDrag(Marker marker) {
        //              //
        //          }
        //          public void onMarkerDragEnd(Marker marker) {
        //              //?
        //          }
        //          public void onMarkerDragStart(Marker marker) {
        //              //
        //          }
        //      });
        //      NotifyLister mNotifyer = new NotifyLister();
        //      mNotifyer.SetNotifyLocation(42.03249652949337,113.3129895882556,3000,"bd09ll");//4?????????????(gcj02,gps,bd09,bd09ll)
        //      mLocationClient.registerNotify(mNotifyer);
        //      
        //      //????
        //      mLocationClient.removeNotifyEvent(mNotifyer);
        //      
        //      
        mLocationClient.registerLocationListener(myListener); //?
        mLocationClient.start();
        // mLocationClient.requestLocation();
    }

    //??????SetNotifyLocation ?????
    //BDNotifyListner
    public class NotifyLister extends BDNotifyListener {
        public void onNotify(BDLocation mlocation, float distance) {
            mVibrator01.vibrate(1000);//???
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // ??????  
        switch (requestCode) {
        case CODE_START:
            startLocation = data.getStringExtra(InputStartActivity.START);
            mStartEdit.setText(startLocation);
            break;
        case CODE_END:
            destination = data.getStringExtra(InputDestActivity.DEST);
            mEndEdit.setText(destination);
            break;
        default:
            break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //activityonDestroymMapView.onDestroy()?  
        mLocationClient.unRegisterLocationListener(myListener);
        mMapView.onDestroy();
        if (null != alertDialog) {
            alertDialog.dismiss();
        }
        if (null != dialog) {
            dialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //activityonResumemMapView. onResume ()?  
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //activityonPausemMapView. onPause ()?  
        mMapView.onPause();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); //GPRS
        option.setAddrType("all");//????
        option.setCoorType("bd09ll");//??,gcj02
        option.setScanSpan(5000); //??5000ms
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @SuppressLint("NewApi")
        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            Log.i("WWQQ", "*&^%$#@!");
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            LatLng point = new LatLng(latitude, longitude);
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.location_arrows);
            OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
            //Marker  
            mBaiduMap.clear();
            mBaiduMap.addOverlay(option);

            if (isFirstGetLocation) {
                //?   MapController
                MapStatus mMapStatus = new MapStatus.Builder().target(point).zoom(17).build();
                //MapStatusUpdate?????? 
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //?? 
                mBaiduMap.setMapStatus(mMapStatusUpdate);
                isFirstGetLocation = false;
            }

            Log.i("WWQQ", "JINGDU:" + longitude);
            Log.i("WWQQ", "WEIDU:" + latitude);
        }
    }

    class sendto_sever extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage("?");
            dialog.setIndeterminate(true);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }

        @SuppressWarnings("deprecation")
        protected String doInBackground(String... arg0) {
            String path = "http://rideserver.jasonbao.com/api/passenger/askRide";
            String uri = path + "?startGeo=" + longitude + "," + latitude + "&p_phone="
                    + Data.getInstance().getmPhone() + "&startLocation=" + startLocation + "&destination="
                    + destination;
            String result = "";
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response;
            try {
                response = static_saving.httpClient.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result == null) {
                alertDialog = new Dialog(MainActivity.this);
                alertDialog.show();
                alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
                LayoutInflater inflater = (LayoutInflater) MainActivity.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View tmp_view = inflater.inflate(R.layout.dialog_login, null);
                TextView tmp_textview = (TextView) tmp_view.findViewById(R.id.dialog_login_text);
                tmp_textview.setText("");
                alertDialog.setContentView(tmp_view);
                return;
            }
            if (null != result && !"".equals(result)) {
                //Log.i("gygyPerson", result);
                try {
                    JSONObject JO_result = new JSONObject(result);
                    String code = JO_result.getString("code");
                    if (code.equals("200")) //????
                    {
                        String str = JO_result.getString("msg");
                        Log.i("WWQQ", str);
                        dialog.setMessage("??");

                        timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                String url = "http://rideserver.jasonbao.com/api/passenger/askRideResult?"
                                        + "p_phone=" + Data.getInstance().getmPhone();
                                PollRunnable pollRunnable = new PollRunnable();
                                pollRunnable.setUrl(url);

                                new Thread(pollRunnable).run();

                                if (pollRunnable.getData() != null) {
                                    Message message = new Message();
                                    message.setData(pollRunnable.getData());
                                    message.what = 1;
                                    handler.sendMessage(message);
                                }
                            }
                        };

                        timer.schedule(timerTask, 2000, 2000);

                    } else {
                        String message = JO_result.getString("msg");//?
                        alertDialog = new Dialog(MainActivity.this);
                        alertDialog.show();
                        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
                        LayoutInflater inflater = (LayoutInflater) MainActivity.this
                                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View tmp_view = inflater.inflate(R.layout.dialog_login, null);
                        TextView tmp_textview = (TextView) tmp_view.findViewById(R.id.dialog_login_text);
                        tmp_textview.setText("GPS???");
                        alertDialog.setContentView(tmp_view);
                        dialog.dismiss();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i("212121", result);
                }
            }
        }
    }

    /**
    * ?Cookie
    */
    public static void savePreference(Context context, String key, String value) {
        SharedPreferences preference = context.getSharedPreferences("COOKIE", Context.MODE_PRIVATE);
        Editor editor = preference.edit();
        editor.putString(key, value);
        Log.i("WWQQ", "saving preferences.   key:" + key + " value:" + value);
        editor.commit();//
    }

    private void getCookie(HttpClient httpClient) {
        Log.i("WWQQ", "IN GETCOOKIE");
        List cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = (Cookie) cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName) && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        Log.i("WWQQ", "cookie is :" + sb);
        savePreference(this, "SID", sb.toString());
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i("WWQQ", "Polling Result............. ");
            if (msg.what == 1) {
                String result = msg.getData().getString("result");
                Log.i("WWQQ", "Polling Result: " + result);
                JSONObject JO_result;
                try {
                    JO_result = new JSONObject(result);
                    String code = JO_result.getString("code");
                    if (code.equals("200")) //????
                    {
                        JSONObject obj_inner = JO_result.getJSONObject("msg");
                        String d_phone = obj_inner.getString("d_phone");
                        String username = obj_inner.getString("username");
                        String photo = obj_inner.getString("photo");
                        String model = obj_inner.getString("model");
                        String license = obj_inner.getString("license");
                        String rate = obj_inner.getString("rate");
                        JSONObject location = obj_inner.getJSONObject("currentGeo");
                        double driver_longitude = location.getDouble("longitude");
                        double driver_latitude = location.getDouble("latitude");
                        timer.cancel();

                        Intent i = new Intent(MainActivity.this, WaitHeComeActivity.class);

                        i.putExtra(WaitHeComeActivity.DRIVERNAME, username);
                        i.putExtra(WaitHeComeActivity.DRIVEAVATAR, photo);
                        i.putExtra(WaitHeComeActivity.DRIVERPHONE, d_phone);
                        i.putExtra(WaitHeComeActivity.DRIVERLICENSE, license);
                        i.putExtra(WaitHeComeActivity.DRIVERMODEL, model);
                        i.putExtra(WaitHeComeActivity.DRIVERSTARS, rate);
                        i.putExtra(WaitHeComeActivity.DRIVERDEALNUM, 25); //??
                        startActivity(i);
                        finish();
                    } else {
                        Log.i("WWQQ", "NO ORDER NOW ............");
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    };
}