MainActivity.java 86.7 KB
Newer Older
V
Vergil 已提交
1 2 3
package com.example.mockgps;

import android.Manifest;
4
import android.annotation.SuppressLint;
V
Vergil 已提交
5
import android.annotation.TargetApi;
6
import android.app.PendingIntent;
V
Vergil 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
33
import android.support.v4.app.ActivityCompat;
V
Vergil 已提交
34 35 36
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
37
import android.telephony.TelephonyManager;
V
Vergil 已提交
38
import android.util.Log;
39
import android.view.Display;
V
Vergil 已提交
40
import android.view.Gravity;
41
import android.view.LayoutInflater;
V
Vergil 已提交
42 43 44 45 46 47 48 49 50 51 52 53
import android.view.MotionEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.CheckBox;
54
import android.widget.EditText;
V
Vergil 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
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.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.service.HistoryDBHelper;
import com.example.service.MockGpsService;
V
Vergil 已提交
101
import com.example.service.SearchDBHelper;
V
Vergil 已提交
102 103 104 105 106 107
import com.example.service.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

108
import java.lang.reflect.Method;
V
Vergil 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mapapi.overlayutil.PoiOverlay;

import static com.example.service.MockGpsService.RunCode;
import static com.example.service.MockGpsService.StopCode;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SensorEventListener {

    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;

    //位置欺骗相关
V
Vergil 已提交
127
    //  latLngInfo  经度&纬度
V
Vergil 已提交
128 129 130 131 132 133
    public static String latLngInfo = "104.06121778639009&30.544111926165282";
    private boolean isMockLocOpen = false;
    private MockGpsService mockGpsService;
    private MockServiceReceiver mockServiceReceiver = null;
    private boolean isServiceRun = false;
    private boolean isMockServStart = false;
134
    private boolean isGPSOpen = false;
V
Vergil 已提交
135 136

    //sqlite相关
V
Vergil 已提交
137
    //定位历史
V
Vergil 已提交
138
    private HistoryDBHelper historyDBHelper;
V
Vergil 已提交
139 140 141 142 143
    private SQLiteDatabase locHistoryDB;
    //搜索历史
    private SearchDBHelper searchDBHelper;
    private SQLiteDatabase searchHistoryDB;

V
Vergil 已提交
144 145 146 147 148
    private boolean isSQLiteStart = false;


    //http
    private RequestQueue mRequestQueue;
V
Vergil 已提交
149
    private boolean isNetworkConnected = true;
V
Vergil 已提交
150 151

    // 定位相关
152
    LocationClient mLocClient = null;
V
Vergil 已提交
153 154 155 156 157 158 159 160 161
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
V
Vergil 已提交
162
    private String mCurrentCity = "成都市";
V
Vergil 已提交
163 164 165 166 167 168 169 170 171 172
    private String mCurrentAddr;
    /**
     * 当前地点击点
     */
    public static LatLng currentPt = new LatLng(30.547743718042415, 104.07018449827267);
    public static BitmapDescriptor bdA = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_gcoding);


    public MapView mMapView;
173
    public static BaiduMap mBaiduMap = null;
V
Vergil 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

    // UI相关
    RadioGroup.OnCheckedChangeListener radioButtonListener;
    RadioGroup.OnCheckedChangeListener radioButtonListener2;
    //Button requestLocButton;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;

    private RadioGroup grouploc;
    private RadioGroup groupmap;

    private FloatingActionButton fab;
    private FloatingActionButton fabStop;

    //位置搜索相关
    PoiSearch poiSearch;
    private SearchView searchView;
    private ListView searchlist;
V
Vergil 已提交
192
    private ListView historySearchlist;
V
Vergil 已提交
193 194
    private SimpleAdapter simAdapt;
    private LinearLayout mlinearLayout;
V
Vergil 已提交
195
    private LinearLayout mHistorylinearLayout;
V
Vergil 已提交
196 197 198 199 200 201 202 203
    private MenuItem searchItem;
    private boolean isSubmit;
    private SuggestionSearch mSuggestionSearch;
    ////////

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
V
Vergil 已提交
204 205 206 207


        Log.d("PROGRESS", "isMockServStart=" + isMockServStart);
        Log.d("PROGRESS", "onCreate");
V
Vergil 已提交
208 209 210 211
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
212

V
Vergil 已提交
213 214 215
        //sqlite
        try {
            historyDBHelper = new HistoryDBHelper(getApplicationContext());
V
Vergil 已提交
216 217 218
            locHistoryDB = historyDBHelper.getWritableDatabase();
            searchDBHelper = new SearchDBHelper(getApplicationContext());
            searchHistoryDB = searchDBHelper.getWritableDatabase();
V
Vergil 已提交
219
            isSQLiteStart = true;
V
Vergil 已提交
220
//            historyDBHelper.onUpgrade(locHistoryDB,locHistoryDB.getVersion(),locHistoryDB.getVersion());
V
Vergil 已提交
221
        } catch (Exception e) {
V
Vergil 已提交
222
            Log.e("DATABASE", "sqlite init error");
V
Vergil 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
            isSQLiteStart = false;
            e.printStackTrace();
        }

        //set fab listener
        setFabListener();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //http init
        mRequestQueue = Volley.newRequestQueue(this);

        //注册MockService广播接收器
        try {
            mockServiceReceiver = new MockServiceReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.example.service.MockGpsService");
//            this.unregisterReceiver(mockServiceReceiver);
            this.registerReceiver(mockServiceReceiver, filter);
        } catch (Exception e) {
V
Vergil 已提交
250
            Log.e("UNKNOWN", "registerReceiver error");
V
Vergil 已提交
251 252 253 254 255
            e.printStackTrace();
        }


        //获取权限
V
Vergil 已提交
256
        getPersimmions();
V
Vergil 已提交
257 258 259 260 261 262 263
        /////
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        //RadioGroup
        setGroupListener();

        //网络是否可用
V
Vergil 已提交
264
        if (!isNetworkAvailable()) {
V
Vergil 已提交
265
            DisplayToast("网络连接不可用,请检查网络连接设置");
V
Vergil 已提交
266
            isNetworkConnected = false;
V
Vergil 已提交
267 268
        }

269 270 271 272 273
        //gps是否开启
//        isGPSOpen=isGpsOpened();
        if (!(isGPSOpen = isGpsOpened())) {
            DisplayToast("GPS定位未开启,请先打开GPS定位服务");
        }
V
Vergil 已提交
274 275 276 277 278

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        initListener();
279

V
Vergil 已提交
280 281
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
282 283 284 285 286 287 288 289 290

        //开启定位图层
        if (!isGPSOpen) {
            //如果未打开GPS,跳转到定位设置界面
            showGpsDialog();
        } else {
            //如果GPS定位开启,则打开定位图层
            openLocateLayer();
        }
V
Vergil 已提交
291 292 293 294 295 296

        //poi search 实例化
        poiSearch = PoiSearch.newInstance();
        //搜索相关
        searchView = (SearchView) findViewById(R.id.action_search);
        searchlist = (ListView) findViewById(R.id.search_list_view);
V
Vergil 已提交
297 298 299 300 301
        mlinearLayout = (LinearLayout) findViewById(R.id.search_linear);

        historySearchlist = (ListView) findViewById(R.id.search_history_list_view);
        mHistorylinearLayout = (LinearLayout) findViewById(R.id.search_history_linear);

V
Vergil 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        // 是否开启位置模拟
        isMockLocOpen = isAllowMockLocation();
        //提醒用户开启位置模拟
        if (!isMockLocOpen) {
            setDialog();
        }
        //悬浮窗权限判断
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
        //初始化POI搜索监听
V
Vergil 已提交
317
        initPoiSearchResultListener();
V
Vergil 已提交
318 319
        //搜索结果列表的点击监听
        setSearchRetClickListener();
V
Vergil 已提交
320 321
        //搜索历史列表的点击监听
        setHistorySearchClickListener();
V
Vergil 已提交
322 323 324 325 326
        //设置搜索建议返回值监听
        setSugSearchListener();
        //初始位置随机处理
        randomFix();
        //如果网络不可用,地图中心点置为最新定位点
V
Vergil 已提交
327
        LatLng latLng = getLatestLocation(locHistoryDB, HistoryDBHelper.TABLE_NAME);
V
Vergil 已提交
328 329 330
        MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(mapstatusupdate);

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        //一个子线程,检测GPS定位是否开启
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 写子线程中的操作
                while (!isGpsOpened()) {
                    Log.d("GPS", "gps not open");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                isGPSOpen = true;
                Log.d("GPS", "gps opened");
                //如果GPS定位开启,打开定位图层
                openLocateLayer();
            }
        }).start();
V
Vergil 已提交
350

351 352
//        func();
        //for debug
V
Vergil 已提交
353 354 355 356 357

    }

    //for debug
    public void func() {
358
        // for test
V
Vergil 已提交
359 360 361 362


    }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    //显示开启GPS的提示
    private void showGpsDialog() {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Tips")//这里是表头的内容
                .setMessage("是否开启GPS定位服务?")//这里是中间显示的具体信息
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent, 0);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                .show();
    }

    //显示输入经纬度的对话框
    public void showLatlngDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("输入经度和纬度(BD09坐标系)");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.latlng_dialog, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);

        final EditText dialog_lng = (EditText) view.findViewById(R.id.dialog_longitude);
        final EditText dialog_lat = (EditText) view.findViewById(R.id.dialog_latitude);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String dialog_lng_str = "", dialog_lat_str = "";
                try {
                    dialog_lng_str = dialog_lng.getText().toString().trim();
                    dialog_lat_str = dialog_lat.getText().toString().trim();
                    double dialog_lng_double = Double.valueOf(dialog_lng_str);
                    double dialog_lat_double = Double.valueOf(dialog_lat_str);
//                    DisplayToast("经度: " + dialog_lng_str + ", 纬度: " + dialog_lat_str);
                    if (dialog_lng_double > 180.0 || dialog_lng_double < -180.0 || dialog_lat_double > 90.0 || dialog_lat_double < -90.0) {
                        DisplayToast("经纬度超出限制!\n-180.0<经度<180.0\n-90.0<纬度<90.0");
                    } else {
                        currentPt = new LatLng(dialog_lat_double, dialog_lng_double);
                        MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(currentPt);
                        //对地图的中心点进行更新
                        mBaiduMap.setMapStatus(mapstatusupdate);
                        updateMapState();
                        transformCoordinate(dialog_lng_str, dialog_lat_str);
                    }
                } catch (Exception e) {
                    DisplayToast("获取经纬度出错,请检查输入是否正确");
                    e.printStackTrace();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    //判断GPS是否打开
    private boolean isGpsOpened() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    //开启百度地图的定位图层
    private void openLocateLayer() {
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    //获取IMEI
    public String getIMEI(Context context, int slotId) {
        try {
            TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            assert manager != null;
            Method method = manager.getClass().getMethod("getImei", int.class);
            String imei = (String) method.invoke(manager, slotId);
            Log.d("IMEI", imei);
            return imei;
        } catch (Exception e) {
            return "";
        }
    }

V
Vergil 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    //获取查询历史
    private List<Map<String, Object>> getSearchHistory() {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

        try {
            Cursor cursor = searchDBHelper.getWritableDatabase().query(SearchDBHelper.TABLE_NAME, null,
                    "ID > ?", new String[]{"0"},
                    null, null, "TimeStamp DESC", null);
            while (cursor.moveToNext()) {
                int ID = cursor.getInt(0);

                Map<String, Object> searchHistoryItem = new HashMap<String, Object>();
                searchHistoryItem.put("search_key", cursor.getString(1));
                searchHistoryItem.put("search_description", cursor.getString(2));
                searchHistoryItem.put("search_timestamp", "" + cursor.getInt(3));
                searchHistoryItem.put("search_isLoc", "" + cursor.getInt(4));
                searchHistoryItem.put("search_longitude", "" + cursor.getString(7));
                searchHistoryItem.put("search_latitude", "" + cursor.getString(8));

                data.add(searchHistoryItem);

            }
            // 关闭光标
            cursor.close();
        } catch (Exception e) {
            Log.e("DATABASE", "query error");
            e.printStackTrace();
        }
        return data;
V
Vergil 已提交
494 495 496
    }

    //WIFI是否可用
V
Vergil 已提交
497
    private boolean isWifiConnected() {
V
Vergil 已提交
498 499 500 501 502 503 504 505 506 507
        ConnectivityManager mConnectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWiFiNetworkInfo != null) {
            return mWiFiNetworkInfo.isAvailable();
        }
        return false;
    }

    //MOBILE网络是否可用
V
Vergil 已提交
508
    private boolean isMobileConnected() {
V
Vergil 已提交
509 510 511 512 513 514 515 516 517 518
        ConnectivityManager mConnectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mMobileNetworkInfo = mConnectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mMobileNetworkInfo != null) {
            return mMobileNetworkInfo.isAvailable();
        }
        return false;
    }

    //网络是否可用
V
Vergil 已提交
519 520
    private boolean isNetworkAvailable() {
        return isWifiConnected() || isMobileConnected();
V
Vergil 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    }

    //位置随机处理
    private void randomFix() {
        double ra1 = Math.random() * 2.0 - 1.0;
        double ra2 = Math.random() * 2.0 - 1.0;
        double randLng = 104.07018449827267 + ra1 / 2000.0;
        double randLat = 30.547743718042415 + ra2 / 2000.0;
        currentPt = new LatLng(randLat, randLng);
        transformCoordinate(Double.toString(randLng), Double.toString(randLat));
    }

    //set group button listener
    private void setGroupListener() {
        grouploc = (RadioGroup) this.findViewById(R.id.RadioGroupLocType);
        radioButtonListener2 = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.normalloc) {
//                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                    mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
                    mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                            mCurrentMode, true, mCurrentMarker));
                    MapStatus.Builder builder1 = new MapStatus.Builder();
                    builder1.overlook(0);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));
                }
                if (checkedId == R.id.trackloc) {
//                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                    mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                    mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                            mCurrentMode, true, mCurrentMarker));
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.overlook(0);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                if (checkedId == R.id.compassloc) {
//                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                    mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
                    mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                            mCurrentMode, true, mCurrentMarker));
                }
            }
        };
        grouploc.setOnCheckedChangeListener(radioButtonListener2);


        groupmap = (RadioGroup) this.findViewById(R.id.RadioGroup);
        radioButtonListener = new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.normal) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                }
                if (checkedId == R.id.statellite) {
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                }
            }
        };
        groupmap.setOnCheckedChangeListener(radioButtonListener);
    }

    //set float action button listener
    private void setFabListener() {
        //应用内悬浮按钮
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fabStop = (FloatingActionButton) findViewById(R.id.fabStop);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /////
592 593 594
                if (!isGPSOpen) {
                    //如果GPS未开启
                    showGpsDialog();
V
Vergil 已提交
595
                } else {
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
                    if (!(isMockLocOpen = isAllowMockLocation())) {
                        setDialog();
                    } else {
                        if (!isMockServStart && !isServiceRun) {
                            Log.d("DEBUG", "current pt is " + currentPt.longitude + "  " + currentPt.latitude);
                            updateMapState();
                            //start mock location service
                            Intent mockLocServiceIntent = new Intent(MainActivity.this, MockGpsService.class);
                            mockLocServiceIntent.putExtra("key", latLngInfo);
                            //isFisrtUpdate=false;
                            //save record
                            updatePositionInfo();
                            //insert end
                            if (Build.VERSION.SDK_INT >= 26) {
                                startForegroundService(mockLocServiceIntent);
                                Log.d("DEBUG", "startForegroundService:MOCK_GPS");
                            } else {
                                startService(mockLocServiceIntent);
                                Log.d("DEBUG", "startService:MOCK_GPS");
                            }
                            isMockServStart = true;
                            Snackbar.make(view, "位置模拟已开启", Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                            fab.setVisibility(View.INVISIBLE);
                            fabStop.setVisibility(View.VISIBLE);
                            //track
                            grouploc.check(R.id.trackloc);
V
Vergil 已提交
623
                        } else {
624 625 626 627 628
                            Snackbar.make(view, "位置模拟已在运行", Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                            fab.setVisibility(View.INVISIBLE);
                            fabStop.setVisibility(View.VISIBLE);
                            isMockServStart = true;
V
Vergil 已提交
629 630 631
                        }
                    }
                }
632

V
Vergil 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
            }
        });

        fabStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMockServStart) {
                    //end mock location
                    Intent mockLocServiceIntent = new Intent(MainActivity.this, MockGpsService.class);
                    stopService(mockLocServiceIntent);
                    Snackbar.make(v, "位置模拟服务终止", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                    //service finish
                    isMockServStart = false;
                    fab.setVisibility(View.VISIBLE);
                    fabStop.setVisibility(View.INVISIBLE);
                    //重新定位
                    mLocClient.stop();
                    mLocClient.start();
                    //normal
                    grouploc.check(R.id.normalloc);
                    //clear
//                    mBaiduMap.clear();
                }
            }
        });
    }

    //设置search list 点击监听
    private void setSearchRetClickListener() {
        searchlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String lng = ((TextView) view.findViewById(R.id.poi_longitude)).getText().toString();
                String lat = ((TextView) view.findViewById(R.id.poi_latitude)).getText().toString();
//                DisplayToast("lng is "+lng+"lat is "+lat);
                currentPt = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
                MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(currentPt);
                //对地图的中心点进行更新,
                mBaiduMap.setMapStatus(mapstatusupdate);
                updateMapState();
                transformCoordinate(lng, lat);
//                searchlist.setVisibility(View.GONE);
V
Vergil 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694

                //搜索历史 插表参数
                ContentValues contentValues = new ContentValues();
                contentValues.put("SearchKey", ((TextView) view.findViewById(R.id.poi_name)).getText().toString());
                contentValues.put("Description", ((TextView) view.findViewById(R.id.poi_addr)).getText().toString());
                contentValues.put("IsLocate", 1);
                contentValues.put("BD09Longitude", lng);
                contentValues.put("BD09Latitude", lat);
                String wgsLatLngStr[] = latLngInfo.split("&");
                contentValues.put("WGS84Longitude", wgsLatLngStr[0]);
                contentValues.put("WGS84Latitude", wgsLatLngStr[1]);
                contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);

                if (!insertHistorySearchTable(searchHistoryDB, SearchDBHelper.TABLE_NAME, contentValues)) {
                    Log.e("DATABASE", "insertHistorySearchTable[SearchHistory] error");
                } else {
                    Log.d("DATABASE", "insertHistorySearchTable[SearchHistory] success");
                }

V
Vergil 已提交
695 696 697 698 699 700 701
                mlinearLayout.setVisibility(View.INVISIBLE);
                searchItem.collapseActionView();
//                transformCoordinate();
            }
        });
    }

V
Vergil 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718

    //设置history search list 点击监听
    private void setHistorySearchClickListener() {
        historySearchlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String searchDescription = ((TextView) view.findViewById(R.id.search_description)).getText().toString();
                String searchKey = ((TextView) view.findViewById(R.id.search_key)).getText().toString();
                String searchIsLoc = ((TextView) view.findViewById(R.id.search_isLoc)).getText().toString();

                //如果是定位搜索
                if (searchIsLoc.equals("1")) {
                    String lng = ((TextView) view.findViewById(R.id.search_longitude)).getText().toString();
                    String lat = ((TextView) view.findViewById(R.id.search_latitude)).getText().toString();
//                    DisplayToast("lng is " + lng + "lat is " + lat);
                    currentPt = new LatLng(Double.valueOf(lat), Double.valueOf(lng));
                    MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(currentPt);
719
                    //对地图的中心点进行更新
V
Vergil 已提交
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
                    mBaiduMap.setMapStatus(mapstatusupdate);
                    updateMapState();
                    transformCoordinate(lng, lat);
                    //设置列表不可见
                    mHistorylinearLayout.setVisibility(View.INVISIBLE);
                    searchItem.collapseActionView();
                    //更新表
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("SearchKey", searchKey);
                    contentValues.put("Description", searchDescription);
                    contentValues.put("IsLocate", 1);
                    contentValues.put("BD09Longitude", lng);
                    contentValues.put("BD09Latitude", lat);
                    String wgsLatLngStr[] = latLngInfo.split("&");
                    contentValues.put("WGS84Longitude", wgsLatLngStr[0]);
                    contentValues.put("WGS84Latitude", wgsLatLngStr[1]);
                    contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                    if (!insertHistorySearchTable(searchHistoryDB, SearchDBHelper.TABLE_NAME, contentValues)) {
                        Log.e("DATABASE", "insertHistorySearchTable[SearchHistory] error");
                    } else {
                        Log.d("DATABASE", "insertHistorySearchTable[SearchHistory] success");
                    }
                }
                //如果仅仅是搜索
                else if (searchIsLoc.equals("0")) {
                    try {
//                        resetMap();
                        isSubmit = true;
                        mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())

                                .keyword(searchKey)
                                .city(mCurrentCity)

                        );
                        mBaiduMap.clear();
                        mHistorylinearLayout.setVisibility(View.INVISIBLE);
                        searchItem.collapseActionView();

                        //更新表
                        //搜索历史 插表参数
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("SearchKey", searchKey);
                        contentValues.put("Description", "搜索...");
                        contentValues.put("IsLocate", 0);
                        contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                        if (!insertHistorySearchTable(searchHistoryDB, SearchDBHelper.TABLE_NAME, contentValues)) {
                            Log.e("DATABASE", "insertHistorySearchTable[SearchHistory] error");
                        } else {
                            Log.d("DATABASE", "insertHistorySearchTable[SearchHistory] success");
                        }

                    } catch (Exception e) {
                        DisplayToast("搜索失败,请检查网络连接");
                        e.printStackTrace();
                    }
                }
                //其他情况
                else {

                }


            }
        });
784
        historySearchlist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
V
Vergil 已提交
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Warning")//这里是表头的内容
                        .setMessage("确定要删除该项搜索记录吗?")//这里是中间显示的具体信息
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String searchKey = ((TextView) view.findViewById(R.id.search_key)).getText().toString();
                                        try {
                                            searchHistoryDB.delete(SearchDBHelper.TABLE_NAME, "SearchKey = ?", new String[]{searchKey});
                                            //删除成功
                                            //展示搜索历史
                                            List<Map<String, Object>> data = getSearchHistory();
                                            if (data.size() > 0) {
                                                simAdapt = new SimpleAdapter(
                                                        MainActivity.this,
                                                        data,
                                                        R.layout.history_search_item,
                                                        new String[]{"search_key", "search_description", "search_timestamp", "search_isLoc", "search_longitude", "search_latitude"},// 与下面数组元素要一一对应
                                                        new int[]{R.id.search_key, R.id.search_description, R.id.search_timestamp, R.id.search_isLoc, R.id.search_longitude, R.id.search_latitude});
                                                historySearchlist.setAdapter(simAdapt);
                                                mHistorylinearLayout.setVisibility(View.VISIBLE);
                                            }

                                        } catch (Exception e) {
                                            Log.e("DATABASE", "delete error");
                                            DisplayToast("DELETE ERROR[UNKNOWN]");
                                            e.printStackTrace();
                                        }
//                                        String locID=(String) ((TextView) view.findViewById(R.id.LocationID)).getText();
//                                        boolean deleteRet=deleteRecord(sqLiteDatabase,HistoryDBHelper.TABLE_NAME,Integer.valueOf(locID));
//                                        if (deleteRet){
//                                            DisplayToast("删除成功!");
//                                            initListView();
//                                        }
                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                })
                        .show();

                return true;
            }
        });
    }


V
Vergil 已提交
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
    //poi搜索初始化
    private void initPoiSearchResultListener() {
        OnGetPoiSearchResultListener poiSearchListener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {// 没有找到检索结果
                    DisplayToast("没有找到检索结果");
                    return;
                }
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {// 检索结果正常返回

                    if (isSubmit) {
//                        mBaiduMap.clear();
                        MyPoiOverlay poiOverlay = new MyPoiOverlay(mBaiduMap);
                        poiOverlay.setData(poiResult);// 设置POI数据
                        mBaiduMap.setOnMarkerClickListener(poiOverlay);
                        poiOverlay.addToMap();// 将所有的overlay添加到地图上
                        poiOverlay.zoomToSpan();
                        mlinearLayout.setVisibility(View.INVISIBLE);
                        //标注搜索点 关闭搜索列表
//                        searchView.clearFocus();  //可以收起键盘
                        searchItem.collapseActionView(); //关闭搜索视图
                        isSubmit = false;

                    } else {
                        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
                        int retCnt = poiResult.getAllPoi().size();
                        for (int i = 0; i < retCnt; i++) {
                            Map<String, Object> testitem = new HashMap<String, Object>();
                            testitem.put("key_name", poiResult.getAllPoi().get(i).name);
                            testitem.put("key_addr", poiResult.getAllPoi().get(i).address);
                            testitem.put("key_lng", "" + poiResult.getAllPoi().get(i).location.longitude);
                            testitem.put("key_lat", "" + poiResult.getAllPoi().get(i).location.latitude);
                            data.add(testitem);
                        }
                        simAdapt = new SimpleAdapter(
                                MainActivity.this,
                                data,
V
Vergil 已提交
877
                                R.layout.poi_search_item,
V
Vergil 已提交
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
                                new String[]{"key_name", "key_addr", "key_lng", "key_lat"},// 与下面数组元素要一一对应
                                new int[]{R.id.poi_name, R.id.poi_addr, R.id.poi_longitude, R.id.poi_latitude});
                        searchlist.setAdapter(simAdapt);
//                    searchlist.setVisibility(View.VISIBLE);
                        mlinearLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
                DisplayToast(poiDetailResult.name);
//                Log.d("DETAIL",poiDetailResult.address);
//                Log.d("DETAIL",poiDetailResult.name);
//                Log.d("DETAIL",poiDetailResult.tag);
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }

        };
        poiSearch.setOnGetPoiSearchResultListener(poiSearchListener);
    }
V
Vergil 已提交
903

V
Vergil 已提交
904
    //检索建议
V
Vergil 已提交
905 906
    private void setSugSearchListener() {
        mSuggestionSearch = SuggestionSearch.newInstance();
V
Vergil 已提交
907 908 909 910 911 912 913 914 915
        OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
            public void onGetSuggestionResult(SuggestionResult res) {

                if (res == null || res.getAllSuggestions() == null) {
                    //未找到相关结果
                    DisplayToast("没有找到检索结果");
                    return;
                }
                //获取在线建议检索结果
V
Vergil 已提交
916
                else {
V
Vergil 已提交
917 918
                    if (isSubmit) {
//                        mBaiduMap.clear();
V
Vergil 已提交
919 920
                        //normal
                        grouploc.check(R.id.normalloc);
V
Vergil 已提交
921 922 923 924 925 926 927 928 929 930 931
                        MyPoiOverlay poiOverlay = new MyPoiOverlay(mBaiduMap);
                        poiOverlay.setSugData(res);// 设置POI数据
                        mBaiduMap.setOnMarkerClickListener(poiOverlay);
                        poiOverlay.addToMap();// 将所有的overlay添加到地图上
                        poiOverlay.zoomToSpan();
                        mlinearLayout.setVisibility(View.INVISIBLE);
                        //标注搜索点 关闭搜索列表
//                        searchView.clearFocus();  //可以收起键盘
                        searchItem.collapseActionView(); //关闭搜索视图
                        isSubmit = false;

V
Vergil 已提交
932
                    } else {
V
Vergil 已提交
933 934 935
                        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
                        int retCnt = res.getAllSuggestions().size();
                        for (int i = 0; i < retCnt; i++) {
V
Vergil 已提交
936
                            if (res.getAllSuggestions().get(i).pt == null) {
V
Vergil 已提交
937 938 939 940
                                continue;
                            }
                            Map<String, Object> poiItem = new HashMap<String, Object>();
                            poiItem.put("key_name", res.getAllSuggestions().get(i).key);
V
Vergil 已提交
941
                            poiItem.put("key_addr", res.getAllSuggestions().get(i).city + " " + res.getAllSuggestions().get(i).district);
V
Vergil 已提交
942 943 944 945 946 947 948
                            poiItem.put("key_lng", "" + res.getAllSuggestions().get(i).pt.longitude);
                            poiItem.put("key_lat", "" + res.getAllSuggestions().get(i).pt.latitude);
                            data.add(poiItem);
                        }
                        simAdapt = new SimpleAdapter(
                                MainActivity.this,
                                data,
V
Vergil 已提交
949
                                R.layout.poi_search_item,
V
Vergil 已提交
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
                                new String[]{"key_name", "key_addr", "key_lng", "key_lat"},// 与下面数组元素要一一对应
                                new int[]{R.id.poi_name, R.id.poi_addr, R.id.poi_longitude, R.id.poi_latitude});
                        searchlist.setAdapter(simAdapt);
//                    searchlist.setVisibility(View.VISIBLE);
                        mlinearLayout.setVisibility(View.VISIBLE);
                    }
                }
            }
        };
        mSuggestionSearch.setOnGetSuggestionResultListener(listener);

    }

    //城市内搜索
    private void citySearch(int page, String city, String key) {
        // 设置检索参数
        PoiCitySearchOption citySearchOption = new PoiCitySearchOption();
        citySearchOption.city(city);// 城市
        citySearchOption.keyword(key);// 关键字
        citySearchOption.pageCapacity(15);// 默认每页10条
        citySearchOption.pageNum(page);// 分页编号
        // 发起检索请求
        poiSearch.searchInCity(citySearchOption);
    }


    //范围检索
    private void boundSearch(int page, double longitude, double latitude, String key) {
        PoiBoundSearchOption boundSearchOption = new PoiBoundSearchOption();
        LatLng southwest = new LatLng(latitude - 0.01, longitude - 0.012);// 西南
        LatLng northeast = new LatLng(latitude + 0.01, longitude + 0.012);// 东北
        LatLngBounds bounds = new LatLngBounds.Builder().include(southwest)
                .include(northeast).build();// 得到一个地理范围对象
        boundSearchOption.bound(bounds);// 设置poi检索范围
        boundSearchOption.keyword(key);// 检索关键字
        boundSearchOption.pageNum(page);
        poiSearch.searchInBound(boundSearchOption);// 发起poi范围检索请求
    }


    //附近检索
    private void nearbySearch(int page, double longitude, double latitude, String key) {
        PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption();
        nearbySearchOption.location(new LatLng(latitude, longitude));
        nearbySearchOption.keyword(key);
        nearbySearchOption.radius(1000);// 检索半径,单位是米
        nearbySearchOption.pageNum(page);
        poiSearch.searchNearby(nearbySearchOption);// 发起附近检索请求
    }

V
Vergil 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    //sqlite 操作 插表HistoryLocation
    private boolean insertHistoryLocTable(SQLiteDatabase sqLiteDatabase, String tableName, ContentValues contentValues) {
        boolean insertRet = true;
        try {
            sqLiteDatabase.insert(tableName, null, contentValues);
        } catch (Exception e) {
            Log.e("DATABASE", "insert error");
            insertRet = false;
            e.printStackTrace();
        }
        return insertRet;
    }

    //sqlite 操作 插表HistoryLocation
    private boolean insertHistorySearchTable(SQLiteDatabase sqLiteDatabase, String tableName, ContentValues contentValues) {
V
Vergil 已提交
1015 1016
        boolean insertRet = true;
        try {
V
Vergil 已提交
1017 1018 1019

            String searchKey = contentValues.get("SearchKey").toString();
            sqLiteDatabase.delete(tableName, "SearchKey = ?", new String[]{searchKey});
V
Vergil 已提交
1020 1021
            sqLiteDatabase.insert(tableName, null, contentValues);
        } catch (Exception e) {
V
Vergil 已提交
1022
            Log.e("DATABASE", "insert error");
V
Vergil 已提交
1023 1024 1025 1026 1027
            insertRet = false;
            e.printStackTrace();
        }
        return insertRet;
    }
V
Vergil 已提交
1028 1029


V
Vergil 已提交
1030
    //sqlite 获取上一次定位位置
V
Vergil 已提交
1031
    private LatLng getLatestLocation(SQLiteDatabase sqLiteDatabase, String tableName) {
V
Vergil 已提交
1032 1033 1034 1035
        try {
            Cursor cursor = sqLiteDatabase.query(tableName, null,
                    "ID > ?", new String[]{"0"},
                    null, null, "TimeStamp DESC", "1");
V
Vergil 已提交
1036
            if (cursor.getCount() == 0) {
V
Vergil 已提交
1037 1038
                randomFix();
                return MainActivity.currentPt;
V
Vergil 已提交
1039
            } else {
V
Vergil 已提交
1040
                cursor.moveToNext();
V
Vergil 已提交
1041 1042 1043
                String BD09Longitude = cursor.getString(5);
                String BD09Latitude = cursor.getString(6);
                return new LatLng(Double.valueOf(BD09Latitude), Double.valueOf(BD09Longitude));
V
Vergil 已提交
1044 1045
            }

V
Vergil 已提交
1046
        } catch (Exception e) {
V
Vergil 已提交
1047 1048 1049 1050 1051 1052 1053 1054
            e.printStackTrace();
        }
        return MainActivity.currentPt;
    }

    //提醒开启位置模拟的弹框
    private void setDialog() {
        //判断是否开启开发者选项
V
Vergil 已提交
1055 1056 1057 1058 1059 1060 1061
//        boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) > 0);
//        if (!enableAdb) {
//            DisplayToast("请打先开开发者选项");
//            return;
//        }


V
Vergil 已提交
1062 1063 1064 1065 1066 1067 1068
        new AlertDialog.Builder(this)
                .setTitle("启用位置模拟")//这里是表头的内容
                .setMessage("请在开发者选项->选择模拟位置信息应用中进行设置")//这里是中间显示的具体信息
                .setPositiveButton("设置",//这个string是设置左边按钮的文字
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
V
Vergil 已提交
1069 1070 1071
                                try {
                                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                                    startActivity(intent);
1072
                                } catch (Exception e) {
V
Vergil 已提交
1073 1074 1075
                                    DisplayToast("无法跳转到开发者选项,请先确保您的设备已处于开发者模式");
                                    e.printStackTrace();
                                }
V
Vergil 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
                            }
                        })//setPositiveButton里面的onClick执行的是左边按钮
                .setNegativeButton("取消",//这个string是设置右边按钮的文字
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })//setNegativeButton里面的onClick执行的是右边的按钮的操作
                .show();
    }

    //模拟位置权限是否开启
    public boolean isAllowMockLocation() {
        boolean canMockPosition = false;
        if (Build.VERSION.SDK_INT <= 22) {//6.0以下
            canMockPosition = Settings.Secure.getInt(this.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0;
        } else {
            try {
                LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);//获得LocationManager引用
                String providerStr = LocationManager.GPS_PROVIDER;
                LocationProvider provider = locationManager.getProvider(providerStr);
                if (provider != null) {
                    locationManager.addTestProvider(
                            provider.getName()
                            , provider.requiresNetwork()
                            , provider.requiresSatellite()
                            , provider.requiresCell()
                            , provider.hasMonetaryCost()
                            , provider.supportsAltitude()
                            , provider.supportsSpeed()
                            , provider.supportsBearing()
                            , provider.getPowerRequirement()
                            , provider.getAccuracy());
                } else {
                    locationManager.addTestProvider(
                            providerStr
                            , true, true, false, false, true, true, true
                            , Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
                }
                locationManager.setTestProviderEnabled(providerStr, true);
                locationManager.setTestProviderStatus(providerStr, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
                // 模拟位置可用
                canMockPosition = true;
                locationManager.setTestProviderEnabled(providerStr, false);
                locationManager.removeTestProvider(providerStr);
            } catch (SecurityException e) {
                canMockPosition = false;
            }
        }
        return canMockPosition;
    }

    //设置是否显示交通图
    public void setTraffic(View view) {
        mBaiduMap.setTrafficEnabled(((CheckBox) view).isChecked());
    }

    //设置是否显示百度热力图
    public void setBaiduHeatMap(View view) {
        mBaiduMap.setBaiduHeatMapEnabled(((CheckBox) view).isChecked());
    }

    //对地图事件的消息响应
    private void initListener() {
        mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {

            @Override
            public void onTouch(MotionEvent event) {

            }
        });


        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            /**
             * 单击地图
             */
            public void onMapClick(LatLng point) {
                currentPt = point;
//                DisplayToast("BD09\n[纬度:" + point.latitude + "]\n[经度:" + point.longitude + "]");
                //百度坐标系转wgs坐标系
                transformCoordinate(String.valueOf(point.longitude), String.valueOf(point.latitude));
                updateMapState();

            }

            /**
             * 单击地图中的POI点
             */
            public boolean onMapPoiClick(MapPoi poi) {
                currentPt = poi.getPosition();
//                DisplayToast("BD09\n[维度:" + poi.getPosition().latitude + "]\n[经度:" + poi.getPosition().longitude + "]");
                //百度坐标系转wgs坐标系
                transformCoordinate(String.valueOf(poi.getPosition().longitude), String.valueOf(poi.getPosition().latitude));
                updateMapState();
                return false;
            }
        });
        mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() {
            /**
             * 长按地图
             */
            public void onMapLongClick(LatLng point) {
                currentPt = point;
//                DisplayToast("BD09\n[维度:" + point.latitude + "]\n[经度:" + point.longitude + "]");
                //百度坐标系转wgs坐标系
                transformCoordinate(String.valueOf(point.longitude), String.valueOf(point.latitude));
                updateMapState();
            }
        });
        mBaiduMap.setOnMapDoubleClickListener(new BaiduMap.OnMapDoubleClickListener() {
            /**
             * 双击地图
             */
            public void onMapDoubleClick(LatLng point) {
                currentPt = point;
//                DisplayToast("BD09\n[维度:" + point.latitude + "]\n[经度:" + point.longitude + "]");
                //百度坐标系转wgs坐标系
                transformCoordinate(String.valueOf(point.longitude), String.valueOf(point.latitude));
                updateMapState();
            }
        });

        /**
         * 地图状态发生变化
         */
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            public void onMapStatusChangeStart(MapStatus status) {
//                updateMapState();
            }

            @Override
            public void onMapStatusChangeStart(MapStatus status, int reason) {

            }

            public void onMapStatusChangeFinish(MapStatus status) {
//                updateMapState();
            }

            public void onMapStatusChange(MapStatus status) {
//                updateMapState();
            }
        });
    }

    //更新地图状态显示面板
    private void updateMapState() {
V
Vergil 已提交
1224
        Log.d("DEBUG", "updateMapState");
V
Vergil 已提交
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
        if (currentPt != null) {
            MarkerOptions ooA = new MarkerOptions().position(currentPt).icon(bdA);
            mBaiduMap.clear();
            mBaiduMap.addOverlay(ooA);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息,顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    //定位SDK监听函数
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentAddr = location.getAddrStr();
            mCurrentCity = location.getCity();
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息,顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    protected void onPause() {
V
Vergil 已提交
1288
        Log.d("PROGRESS", "onPause");
V
Vergil 已提交
1289 1290 1291 1292 1293 1294
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
V
Vergil 已提交
1295
        Log.d("PROGRESS", "onPause");
V
Vergil 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
V
Vergil 已提交
1305
        Log.d("PROGRESS", "onStop");
V
Vergil 已提交
1306 1307 1308 1309 1310 1311 1312
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
V
Vergil 已提交
1313
        Log.d("PROGRESS", "onDestroy");
V
Vergil 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        //poi search destroy
        poiSearch.destroy();
        mSuggestionSearch.destroy();
        //close db
V
Vergil 已提交
1324 1325
        locHistoryDB.close();
        searchHistoryDB.close();
V
Vergil 已提交
1326 1327 1328 1329
        super.onDestroy();
    }

    public void DisplayToast(String str) {
1330
        Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG);
V
Vergil 已提交
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        toast.setGravity(Gravity.TOP, 0, 220);
        toast.show();
    }


    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限,用户如果禁止,则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            //悬浮窗
//            if (checkSelfPermission(Manifest.permission.SYSTEM_ALERT_WINDOW) != PackageManager.PERMISSION_GRANTED) {
//                permissions.add(Manifest.permission.SYSTEM_ALERT_WINDOW);
//            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次,用户同意或者禁止,只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        //找到searchView
        searchItem = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setIconified(false);//设置searchView处于展开状态
        searchView.onActionViewExpanded();// 当展开无输入内容的时候,没有关闭的图标
        searchView.setIconifiedByDefault(true);//默认为true在框内,设置false则在框外
        searchView.setSubmitButtonEnabled(true);//显示提交按钮

        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                // Do something when collapsed
                menu.setGroupVisible(0, true);
//                searchlist.setVisibility(View.GONE);
                mlinearLayout.setVisibility(View.INVISIBLE);
V
Vergil 已提交
1427
                mHistorylinearLayout.setVisibility(View.INVISIBLE);
V
Vergil 已提交
1428 1429 1430 1431 1432 1433 1434 1435
                return true;  // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                // Do something when expanded
                menu.setGroupVisible(0, false);
                mlinearLayout.setVisibility(View.INVISIBLE);
V
Vergil 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
                //展示搜索历史
                List<Map<String, Object>> data = getSearchHistory();
                if (data.size() > 0) {
                    simAdapt = new SimpleAdapter(
                            MainActivity.this,
                            data,
                            R.layout.history_search_item,
                            new String[]{"search_key", "search_description", "search_timestamp", "search_isLoc", "search_longitude", "search_latitude"},// 与下面数组元素要一一对应
                            new int[]{R.id.search_key, R.id.search_description, R.id.search_timestamp, R.id.search_isLoc, R.id.search_longitude, R.id.search_latitude});
                    historySearchlist.setAdapter(simAdapt);
                    mHistorylinearLayout.setVisibility(View.VISIBLE);
                }


V
Vergil 已提交
1450 1451 1452
                return true;  // Return true to expand action view
            }
        });
V
Vergil 已提交
1453

V
Vergil 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //提交按钮的点击事件
                //do search
                try {
                    isSubmit = true;
//                    poiSearch.searchInCity((new PoiCitySearchOption())
//                            .city(mCurrentCity)
//                            .keyword(query)
//                            .pageCapacity(10)
//                            .pageNum(0));
                    mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())

                            .keyword(query)
                            .city(mCurrentCity)

                    );
V
Vergil 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
                    //搜索历史 插表参数
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("SearchKey", query);
                    contentValues.put("Description", "搜索...");
                    contentValues.put("IsLocate", 0);
                    contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                    if (!insertHistorySearchTable(searchHistoryDB, SearchDBHelper.TABLE_NAME, contentValues)) {
                        Log.e("DATABASE", "insertHistorySearchTable[SearchHistory] error");
                    } else {
                        Log.d("DATABASE", "insertHistorySearchTable[SearchHistory] success");
                    }

V
Vergil 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
                    mBaiduMap.clear();
                    mlinearLayout.setVisibility(View.INVISIBLE);
                } catch (Exception e) {
                    DisplayToast("搜索失败,请检查网络连接");
                    e.printStackTrace();
                }
                //
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //当输入框内容改变的时候回调
V
Vergil 已提交
1497 1498 1499 1500

                //搜索历史置为不可见
                mHistorylinearLayout.setVisibility(View.INVISIBLE);

V
Vergil 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
                if (!newText.equals("")) {
                    //do search
                    //WATCH ME
                    try {
                        mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
                                .keyword(newText)
                                .city(mCurrentCity)
                        );
//                        poiSearch.searchInCity((new PoiCitySearchOption())
//                                .city(mCurrentCity)
//                                .keyword(newText)
//                                .pageCapacity(30)
//                                .pageNum(0));
                    } catch (Exception e) {
                        DisplayToast("搜索失败,请检查网络连接");
                        e.printStackTrace();
                    }
                    //
                }
                return true;
            }
        });

        return true;
    }

V
Vergil 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    //重置地图
    private void resetMap() {
        mBaiduMap.clear();
        MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(new LatLng(mCurrentLat, mCurrentLon));
        //对地图的中心点进行更新
        mBaiduMap.setMapStatus(mapstatusupdate);
        //更新当前位置
        currentPt = new LatLng(mCurrentLat, mCurrentLon);
        transformCoordinate(Double.toString(currentPt.longitude), Double.toString(currentPt.latitude));
    }

V
Vergil 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546
    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_setting) {
V
Vergil 已提交
1547
            try {
V
Vergil 已提交
1548 1549
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
                startActivity(intent);
1550
            } catch (Exception e) {
V
Vergil 已提交
1551 1552
                DisplayToast("无法跳转到开发者选项,请先确保您的设备已处于开发者模式");
                e.printStackTrace();
V
Vergil 已提交
1553
            }
V
Vergil 已提交
1554 1555 1556 1557 1558 1559 1560 1561
            //判断是否开启开发者选项
//            boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);
//            if (!enableAdb) {
//                DisplayToast("请打先开开发者选项");
//            } else {
//                Intent intent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
//                startActivity(intent);
//            }
V
Vergil 已提交
1562 1563
            return true;
        } else if (id == R.id.action_resetMap) {
V
Vergil 已提交
1564
            resetMap();
1565 1566
        } else if (id == R.id.action_input) {
            showLatlngDialog();
V
Vergil 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        }

        return super.onOptionsItemSelected(item);
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_map) {
            // Handle
        } else if (id == R.id.nav_history) {
            Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_localmap) {
            Intent intent = new Intent(MainActivity.this, OfflineMapActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_manage) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
        }
//        else if (id == R.id.nav_share) {
//
//        }
        else if (id == R.id.nav_send) {
            Intent i = new Intent(Intent.ACTION_SEND);
            // i.setType("text/plain"); //模拟器请使用这行
            i.setType("message/rfc822"); // 真机上使用这行
            i.putExtra(Intent.EXTRA_EMAIL,
                    new String[]{"hilavergil@gmail.com"});
            i.putExtra(Intent.EXTRA_SUBJECT, "SUGGESTION");
            startActivity(Intent.createChooser(i,
                    "Select email application."));
1603

V
Vergil 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //坐标转换
    private void transformCoordinate(final String longitude, final String latitude) {
        //参数坐标系:bd09
//        boolean isInCHN=false;
        final double error = 0.00000001;
1616 1617 1618
//        final String mcode = "9D:8B:73:A5:DF:2A:36:3F:84:2D:38:55:BD:0A:57:C5:8F:50:44:69;com.example.mockgps";
        final String mcode = getResources().getString(R.string.safecode);
        final String ak = "iDVeohokAwgulI0Yga4voEoqDaGqxL7y";
V
Vergil 已提交
1619 1620 1621
        //判断bd09坐标是否在国内
        String mapApiUrl = "http://api.map.baidu.com/geoconv/v1/?coords=" + longitude + "," + latitude +
                "&from=5&to=3&ak=" + ak + "&mcode=" + mcode;
1622
//        Log.d("HTTP", mapApiUrl);
V
Vergil 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631
        //bd09坐标转gcj02
        StringRequest stringRequest = new StringRequest(mapApiUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject getRetJson = new JSONObject(response);
                            //如果api接口转换成功
                            if (Integer.valueOf(getRetJson.getString("status")) == 0) {
1632
                                Log.d("HTTP", "call api[bd09_to_gcj02] success");
V
Vergil 已提交
1633 1634 1635 1636 1637
                                JSONArray coordinateArr = getRetJson.getJSONArray("result");
                                JSONObject coordinate = coordinateArr.getJSONObject(0);
                                String gcj02Longitude = coordinate.getString("x");
                                String gcj02Latitude = coordinate.getString("y");

V
Vergil 已提交
1638 1639
                                Log.d("DEBUG", "bd09Longitude is " + longitude);
                                Log.d("DEBUG", "bd09Latitude is " + latitude);
V
Vergil 已提交
1640

V
Vergil 已提交
1641 1642
                                Log.d("DEBUG", "gcj02Longitude is " + gcj02Longitude);
                                Log.d("DEBUG", "gcj02Latitude is " + gcj02Latitude);
V
Vergil 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

                                BigDecimal bigDecimalGcj02Longitude = new BigDecimal(Double.valueOf(gcj02Longitude));
                                BigDecimal bigDecimalGcj02Latitude = new BigDecimal(Double.valueOf(gcj02Latitude));

                                BigDecimal bigDecimalBd09Longitude = new BigDecimal(Double.valueOf(longitude));
                                BigDecimal bigDecimalBd09Latitude = new BigDecimal(Double.valueOf(latitude));

                                double gcj02LongitudeDouble = bigDecimalGcj02Longitude.setScale(9, BigDecimal.ROUND_HALF_UP).doubleValue();
                                double gcj02LatitudeDouble = bigDecimalGcj02Latitude.setScale(9, BigDecimal.ROUND_HALF_UP).doubleValue();
                                double bd09LongitudeDouble = bigDecimalBd09Longitude.setScale(9, BigDecimal.ROUND_HALF_UP).doubleValue();
                                double bd09LatitudeDouble = bigDecimalBd09Latitude.setScale(9, BigDecimal.ROUND_HALF_UP).doubleValue();


V
Vergil 已提交
1656 1657 1658 1659
                                Log.d("DEBUG", "gcj02LongitudeDouble is " + gcj02LongitudeDouble);
                                Log.d("DEBUG", "gcj02LatitudeDouble is " + gcj02LatitudeDouble);
                                Log.d("DEBUG", "bd09LongitudeDouble is " + bd09LongitudeDouble);
                                Log.d("DEBUG", "bd09LatitudeDouble is " + bd09LatitudeDouble);
V
Vergil 已提交
1660 1661 1662 1663 1664 1665


                                //如果bd09转gcj02 结果误差很小  认为该坐标在国外
                                if ((Math.abs(gcj02LongitudeDouble - bd09LongitudeDouble)) <= error && (Math.abs(gcj02LatitudeDouble - bd09LatitudeDouble)) <= error) {
                                    //不进行坐标转换
                                    latLngInfo = longitude + "&" + latitude;
V
Vergil 已提交
1666
                                    Log.d("DEBUG", "OUT OF CHN, NO NEED TO TRANSFORM COORDINATE");
V
Vergil 已提交
1667 1668 1669 1670 1671 1672
//                                    DisplayToast("OUT OF CHN, NO NEED TO TRANSFORM COORDINATE");
                                } else {
                                    //离线转换坐标系
//                                    double latLng[] = Utils.bd2wgs(Double.valueOf(longitude), Double.valueOf(latitude));
                                    double latLng[] = Utils.gcj02towgs84(Double.valueOf(gcj02Longitude), Double.valueOf(gcj02Latitude));
                                    latLngInfo = latLng[0] + "&" + latLng[1];
V
Vergil 已提交
1673
                                    Log.d("DEBUG", "IN CHN, NEED TO TRANSFORM COORDINATE");
V
Vergil 已提交
1674 1675 1676 1677 1678 1679 1680 1681
//                                    DisplayToast("IN CHN, NEED TO TRANSFORM COORDINATE");
                                }
                            }
                            //api接口转换失败 认为在国内
                            else {
                                //离线转换坐标系
                                double latLng[] = Utils.bd2wgs(Double.valueOf(longitude), Double.valueOf(latitude));
                                latLngInfo = latLng[0] + "&" + latLng[1];
V
Vergil 已提交
1682
                                Log.d("DEBUG", "IN CHN, NEED TO TRANSFORM COORDINATE");
V
Vergil 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691
//                                DisplayToast("BD Map Api Return not Zero, ASSUME IN CHN, NEED TO TRANSFORM COORDINATE");
                            }

                        } catch (JSONException e) {
                            Log.e("JSON", "resolve json error");
                            e.printStackTrace();
                            //离线转换坐标系
                            double latLng[] = Utils.bd2wgs(Double.valueOf(longitude), Double.valueOf(latitude));
                            latLngInfo = latLng[0] + "&" + latLng[1];
V
Vergil 已提交
1692
                            Log.d("DEBUG", "IN CHN, NEED TO TRANSFORM COORDINATE");
V
Vergil 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
//                            DisplayToast("Resolve JSON Error, ASSUME IN CHN, NEED TO TRANSFORM COORDINATE");
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //http 请求失败
                Log.e("HTTP", "HTTP GET FAILED");
                //离线转换坐标系
                double latLng[] = Utils.bd2wgs(Double.valueOf(longitude), Double.valueOf(latitude));
                latLngInfo = latLng[0] + "&" + latLng[1];
V
Vergil 已提交
1705
                Log.d("DEBUG", "IN CHN, NEED TO TRANSFORM COORDINATE");
V
Vergil 已提交
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
//                DisplayToast("HTTP Get Failed, ASSUME IN CHN, NEED TO TRANSFORM COORDINATE");
            }
        });
        // 给请求设置tag
        stringRequest.setTag("MapAPI");
        // 添加tag到请求队列
        mRequestQueue.add(stringRequest);
        //离线转换坐标系
//        double latLng[]= Utils.bd2wgs(Double.valueOf(longitude),Double.valueOf(latitude));
//        latLngInfo=longitude+"&"+latitude;
//        latLngInfo=latLng[0]+"&"+latLng[1];
    }

    //根据经纬度更新位置信息 并插表
    private void updatePositionInfo() {
        //参数坐标系:bd09
1722 1723 1724
//        final String mcode = "9D:8B:73:A5:DF:2A:36:3F:84:2D:38:55:BD:0A:57:C5:8F:50:44:69;com.example.mockgps";
        final String mcode = getResources().getString(R.string.safecode);
        final String ak = "iDVeohokAwgulI0Yga4voEoqDaGqxL7y";
V
Vergil 已提交
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
        //bd09坐标的位置信息
        String mapApiUrl = "http://api.map.baidu.com/geocoder/v2/?location=" + currentPt.latitude + "," + currentPt.longitude + "&output=json&pois=1&ak=" + ak + "&mcode=" + mcode;
        StringRequest stringRequest = new StringRequest(mapApiUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject getRetJson = new JSONObject(response);
                            //位置获取成功
                            if (Integer.valueOf(getRetJson.getString("status")) == 0) {
1735
                                Log.d("HTTP", "call api[get_poisition_info] success");
V
Vergil 已提交
1736 1737 1738
                                JSONObject posInfoJson = getRetJson.getJSONObject("result");
                                String formatted_address = posInfoJson.getString("formatted_address");
//                                DisplayToast(tmp);
V
Vergil 已提交
1739
                                Log.d("DEBUG", formatted_address);
V
Vergil 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750

                                //插表参数
                                ContentValues contentValues = new ContentValues();
                                contentValues.put("Location", formatted_address);
                                String latLngStr[] = latLngInfo.split("&");
                                contentValues.put("WGS84Longitude", latLngStr[0]);
                                contentValues.put("WGS84Latitude", latLngStr[1]);
                                contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                                contentValues.put("BD09Longitude", "" + currentPt.longitude);
                                contentValues.put("BD09Latitude", "" + currentPt.latitude);

V
Vergil 已提交
1751 1752
                                if (!insertHistoryLocTable(locHistoryDB, HistoryDBHelper.TABLE_NAME, contentValues)) {
                                    Log.e("DATABASE", "insertHistoryLocTable[HistoryLocation] error");
V
Vergil 已提交
1753
                                } else {
V
Vergil 已提交
1754
                                    Log.d("DATABASE", "insertHistoryLocTable[HistoryLocation] success");
V
Vergil 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
                                }
                            }
                            //位置获取失败
                            else {
                                //插表参数
                                ContentValues contentValues = new ContentValues();
                                contentValues.put("Location", "NULL");
                                String latLngStr[] = latLngInfo.split("&");
                                contentValues.put("WGS84Longitude", latLngStr[0]);
                                contentValues.put("WGS84Latitude", latLngStr[1]);
                                contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                                contentValues.put("BD09Longitude", "" + currentPt.longitude);
                                contentValues.put("BD09Latitude", "" + currentPt.latitude);

V
Vergil 已提交
1769 1770
                                if (!insertHistoryLocTable(locHistoryDB, HistoryDBHelper.TABLE_NAME, contentValues)) {
                                    Log.e("DATABASE", "insertHistoryLocTable[HistoryLocation] error");
V
Vergil 已提交
1771
                                } else {
V
Vergil 已提交
1772
                                    Log.d("DATABASE", "insertHistoryLocTable[HistoryLocation] success");
V
Vergil 已提交
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
                                }
                            }

                        } catch (JSONException e) {
                            Log.e("JSON", "resolve json error");
                            //插表参数
                            ContentValues contentValues = new ContentValues();
                            contentValues.put("Location", "NULL");
                            String latLngStr[] = latLngInfo.split("&");
                            contentValues.put("WGS84Longitude", latLngStr[0]);
                            contentValues.put("WGS84Latitude", latLngStr[1]);
                            contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                            contentValues.put("BD09Longitude", "" + currentPt.longitude);
                            contentValues.put("BD09Latitude", "" + currentPt.latitude);

V
Vergil 已提交
1788 1789
                            if (!insertHistoryLocTable(locHistoryDB, HistoryDBHelper.TABLE_NAME, contentValues)) {
                                Log.e("DATABASE", "insertHistoryLocTable[HistoryLocation] error");
V
Vergil 已提交
1790
                            } else {
V
Vergil 已提交
1791
                                Log.d("DATABASE", "insertHistoryLocTable[HistoryLocation] success");
V
Vergil 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
                            }
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //http 请求失败
                Log.e("HTTP", "HTTP GET FAILED");
                //插表参数
                ContentValues contentValues = new ContentValues();
                contentValues.put("Location", "NULL");
                String latLngStr[] = latLngInfo.split("&");
                contentValues.put("WGS84Longitude", latLngStr[0]);
                contentValues.put("WGS84Latitude", latLngStr[1]);
                contentValues.put("TimeStamp", System.currentTimeMillis() / 1000);
                contentValues.put("BD09Longitude", "" + currentPt.longitude);
                contentValues.put("BD09Latitude", "" + currentPt.latitude);

V
Vergil 已提交
1812 1813
                if (!insertHistoryLocTable(locHistoryDB, HistoryDBHelper.TABLE_NAME, contentValues)) {
                    Log.e("DATABASE", "insertHistoryLocTable[HistoryLocation] error");
V
Vergil 已提交
1814
                } else {
V
Vergil 已提交
1815
                    Log.d("DATABASE", "insertHistoryLocTable[HistoryLocation] success");
V
Vergil 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
                }
            }
        });
        // 给请求设置tag
        stringRequest.setTag("MapAPI");
        // 添加tag到请求队列
        mRequestQueue.add(stringRequest);
    }

    public class MockServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int statusCode;
            Bundle bundle = intent.getExtras();
            assert bundle != null;
            statusCode = bundle.getInt("statusCode");
1832
//            Log.d("DEBUG", statusCode + "");
V
Vergil 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
            if (statusCode == RunCode) {
                isServiceRun = true;
            } else if (statusCode == StopCode) {
                isServiceRun = false;
            }
        }
    }

    public static boolean setHistoryLocation(String bd09Longitude, String bd09Latitude, String wgs84Longitude, String wgs84Latitude) {
        boolean ret = true;
        try {
            if (!bd09Longitude.isEmpty() && !bd09Latitude.isEmpty()) {
                currentPt = new LatLng(Double.valueOf(bd09Latitude), Double.valueOf(bd09Longitude));
                MarkerOptions ooA = new MarkerOptions().position(currentPt).icon(bdA);
                mBaiduMap.clear();
                mBaiduMap.addOverlay(ooA);
                MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(currentPt);
                mBaiduMap.setMapStatus(mapstatusupdate);
                latLngInfo = wgs84Longitude + "&" + wgs84Latitude;

            }
        } catch (Exception e) {
            ret = false;
V
Vergil 已提交
1856
            Log.e("UNKNOWN", "setHistoryLocation error");
V
Vergil 已提交
1857 1858 1859 1860 1861 1862
            e.printStackTrace();
        }
        return ret;
    }

    class MyPoiOverlay extends PoiOverlay {
V
Vergil 已提交
1863
        private MyPoiOverlay(BaiduMap arg0) {
V
Vergil 已提交
1864 1865 1866 1867 1868 1869
            super(arg0);
        }

        @Override
        public boolean onPoiClick(int arg0) {
            super.onPoiClick(arg0);
V
Vergil 已提交
1870 1871
            PoiResult poiResult = getPoiResult();
            if (poiResult != null && poiResult.getAllPoi() != null) {
V
Vergil 已提交
1872 1873 1874 1875 1876 1877 1878 1879
                PoiInfo poiInfo;
                poiInfo = poiResult.getAllPoi().get(arg0);
                currentPt = poiInfo.location;
                transformCoordinate(Double.toString(currentPt.longitude), Double.toString(currentPt.latitude));
                // 检索poi详细信息
                poiSearch.searchPoiDetail(new PoiDetailSearchOption()
                        .poiUid(poiInfo.uid));
            }
V
Vergil 已提交
1880 1881
            SuggestionResult suggestionResult = getSugResult();
            if (suggestionResult != null && suggestionResult.getAllSuggestions() != null) {
V
Vergil 已提交
1882
                SuggestionResult.SuggestionInfo suggestionInfo;
V
Vergil 已提交
1883
                suggestionInfo = suggestionResult.getAllSuggestions().get(arg0);
V
Vergil 已提交
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
                currentPt = suggestionInfo.pt;
                transformCoordinate(Double.toString(currentPt.longitude), Double.toString(currentPt.latitude));
                // 检索sug详细信息
                poiSearch.searchPoiDetail(new PoiDetailSearchOption()
                        .poiUid(suggestionInfo.uid));
            }
            return true;
        }
    }

}