高德開發記錄:
請尊重原創,本原創部落客為zs2538596--求知欲!!!
由于本人要做的APP是一個軌迹記錄的一個應用,在最初的設計中沒有考慮到手機在上鎖休眠的時候會停止内部GPS和GPRS硬體,這樣就不會擷取坐标的資訊,是以也就無法實時的進行繪制軌迹了。對于怎麼簡單的填充高德地圖,怎麼使用高德地圖,在高德地圖官網上有詳細的說明哦!!
對于鎖屏之後的一些狀态的認識:
在手機鎖屏狀态下,基站資訊是不會更新,位置資訊不會發生變化。但是當解鎖後,會重新請求定位,然後改變定位的位置。大家可以拿出自己的手機,看一下,當鎖屏一段時間後,再打開手機解鎖的時候可以看見手機信号從無變成了滿BUFF~~.
對于Wifi或者GPRS這些東西,也可以觀察到,當手機從休眠到->鎖屏界面再到->解鎖之後,那個Wifi信号會從無信号量轉換到有信号,而那個GPRS信号圖示也會從沒有到有,而且會首先發送向上請求也就是擷取基站的相關資訊。
那麼如何避免讓這些硬體進行休眠呢?
1.如果對實時性要求不高,而且對耗電量要求較高的話建議使用 Alarm方式來定時喚醒,進行擷取坐标,然後記錄軌迹的操作。這種方法可以省些電量,而且每次Alarm間隔的時間越長那麼則越省電。。。。
2.使用Andriod中的電源管理相關的API,這種方法可以讓手機一直處于工作狀态,這個技術做的“最好”的是微信!!!大家可以下載下傳 Wakelock Detector APP觀察一下自己的手機有多少應用是調用了相關的電源管理的API。用了之後你可以看到微信這個APP的始終名列前茅~~~,成為耗電量大老虎~~再此鄙視一下微信

。當然我的小APP的應用也是采用了這種方法~~~但是程式關閉了之後就不會在背景繼續工作~~隻有在開啟的過程中才會不讓手機進入休眠狀态。
是以本人用了一下的代碼,這個代碼可以輕松的在網絡中找到~~擷取電源管理的鎖機制:
private WakeLock wakeLock = null;
private void acquireWakeLock() {
if (wakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
然後将擷取鎖機制放在Activity的onResume狀态下,釋放鎖機制放在onPause狀态下,讓其成對出現,避免讓該activity一直hold者不放~~
OK。。通過擷取電源管理的方法解決了手機鎖屏休眠的問題了,這樣手機的GPS和GPRS就可以一直工作了~~~
如何解決實時定位的問題呢?由于Acitity有生命周期循環的限制,這樣當使用者進行一些操作的時候就會造成相應的Activity進入onPause等聲明周期的狀态,這樣一些activiy相關的操作就不會進行了,是以最好采用Service的方法,即将定位的功能放在Service中來進行,然後讓Activity與該Service進行通信即可。
本人采用的方法為:Service綁定+Broadcast Reciver
目的是:
1、綁定是為了可以讓Activity擷取到Service内部的一些操作方法
2、Broadcast Reciver方法是為了能夠讓Serivce中的資訊能夠實時的回報到Acitvity的界面上,進行相關界面重新整理的操作。
注:本APP中采用了科大訊飛的語音,代碼中的XXX.playText為相關的語音操作~~~~
本人的Broadcast Reciver中進行了相關的軌迹記錄和界面更新的操作,代碼如下:
private IntentFilter filter = new IntentFilter(
StaticData.LOCATION_DATA_BRODCAST_INTENT);
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
provider = intent.getStringExtra(StaticData.PROVIDER);
if (latitude != intent.getDoubleExtra(StaticData.LATITUDE, 0)
&& longitude != intent.getDoubleExtra(StaticData.LONGITUDE,
0)) {
if (start) {
latlng = new LatLng(latitude, longitude);
LatLng temp = new LatLng(intent.getDoubleExtra(
StaticData.LATITUDE, 0), intent.getDoubleExtra(
StaticData.LONGITUDE, 0));
float temp_distance = AMapUtils.calculateLineDistance(
latlng, temp);//計算行走的距離
if (provider.equals("lbs")) {//選擇計算速度的方式
if (temp_distance <= 60) {
speed = temp_distance / 5 * 3.6;
totaldistance += temp_distance / 1000;
voice.playText("目前速度為" + df.format(speed) + "千米每小時");
} else {
speed = temp_distance / 5 * 3.6;
totaldistance += temp_distance / 1000;
voice.playText("目前速度為" + df.format(speed)
+ "千米每小時,速度有些過快");
}
} else if (provider.equals("gps")) {
speed = intent.getDoubleExtra(StaticData.SPEED, 0);
voice.playText("目前速度為" + df.format(speed) + "千米每小時");
}
if (speed >= maxspeed) {
maxspeed = (float) speed;
}
speedtext.setText("速度:" + df.format(speed) + "km/h");//語音提示的相關操作
DrawRideTrace(latlng, temp);
}
latitude = intent.getDoubleExtra(StaticData.LATITUDE, 0);
longitude = intent.getDoubleExtra(StaticData.LONGITUDE, 0);
}
if (start) {
t++;
h = t / 3600;
m = t % 3600 / 60;
s = t % 3600 % 60;
timetext.setText("時間:" + h + "h:" + m + "m:" + s + "s");
if (m == 10) {
voice.playText("您已經騎行" + df.format(totaldistance) + "千米");
}
}
mlatitude = intent.getDoubleExtra(StaticData.LATITUDE, 0);
mlongitude = intent.getDoubleExtra(StaticData.LONGITUDE, 0);
if (closeinit && locationservice != null) {
duration++;
setLocationIcon();
if (duration == 6) {
duration = 0;
closeinit = false;
startup.setVisibility(View.GONE);
}
}
}
};
這個是我的相關背景的定位操作代碼:
public class LocationService extends Service implements AMapLocationListener,
LocationSource {
private LocationManagerProxy mAMapLocationManager;
private Timer timer = null;
private TimerTask task = null;
private double latitude, longitude, speed;
private Intent ServiceIntent = null;
private double distance;
private OnLocationChangedListener mListener;
private boolean change = false;
private AMapLocation mLocation;
private VoiceService voice;
private String provider = null;
// *****************定時發送Intent消息*******************
public void startTimer() {
if (timer == null) {
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
if (ServiceIntent == null) {
ServiceIntent = new Intent(
StaticData.LOCATION_DATA_BRODCAST_INTENT);
}
ServiceIntent.putExtra(StaticData.LATITUDE, latitude);
ServiceIntent.putExtra(StaticData.LONGITUDE, longitude);
ServiceIntent.putExtra(StaticData.SPEED, speed);
ServiceIntent.putExtra(StaticData.PROVIDER, provider);
sendBroadcast(ServiceIntent);
}
};
timer.schedule(task, 1000, 1000);
}
}
public void stopTimer() {
if (timer != null) {
task.cancel();
timer.cancel();
timer = null;
task = null;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return servicebinder;
}
public final LocationServiceBinder servicebinder = new LocationServiceBinder();
public class LocationServiceBinder extends Binder {
public LocationService getLocationService() {
return LocationService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
startTimer();
VoiceService VoiceManager = VoiceService.getInstance(this);// 語音初始化
VoiceManager.init();
voice = VoiceManager;
mAMapLocationManager = LocationManagerProxy.getInstance(this);
mAMapLocationManager.requestLocationData(
LocationProviderProxy.AMapNetwork, 5 * 1000, 10, this);
mAMapLocationManager.setGpsEnable(true);
}
@Override
public void onDestroy() {
stopTimer();
deactivate();
super.onDestroy();
}
// service重新開機需要進行的操作
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mAMapLocationManager != null) {
startTimer();
mAMapLocationManager.requestLocationData(
LocationProviderProxy.AMapNetwork, 5 * 1000, 10, this);
}
if (voice == null) {
VoiceService VoiceManager = VoiceService.getInstance(this);// 鍒濆鍖栬闊蟲ā鍧�
VoiceManager.init();
voice = VoiceManager;
}
return START_STICKY;
}
// service内部變量擷取函數
public OnLocationChangedListener getonLocationChanged() {
return mListener;
}
public AMapLocation getLocaion() {
return mLocation;
}
public VoiceService getVoice() {
return voice;
}
// **********************相關定位操作**********************
@Override
public void onLocationChanged(Location location) {
//已經廢除,采用高德提供的函數接口
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(AMapLocation aLocation) {
if (mListener != null && aLocation != null
&& aLocation.getAMapException().getErrorCode() == 0) {
latitude = aLocation.getLatitude();
longitude = aLocation.getLongitude();
if (aLocation.getProvider().equals("gps")) {
speed = aLocation.getSpeed();
provider = "gps";
} else if (aLocation.getProvider().equals("lbs")) {
provider = "lbs";
}
mListener.onLocationChanged(aLocation);
}
}
//實作LocationSource接口必須實作的方法
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mAMapLocationManager == null) {
mAMapLocationManager = LocationManagerProxy.getInstance(this);
mAMapLocationManager.requestLocationData(
LocationProviderProxy.AMapNetwork, 5 * 1000, 10, this);
mAMapLocationManager.setGpsEnable(true);
}
}
@Override
public void deactivate() {
mListener = null;
if (mAMapLocationManager != null) {
mAMapLocationManager.setGpsEnable(false);
mAMapLocationManager.removeUpdates(this);
mAMapLocationManager.destory();
}
mAMapLocationManager = null;
}
}
</pre><p></p><pre>
這段代碼是使用定位源的地方:
private void setLocationIcon() {
// 自定義系統定位小藍點
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory
.fromResource(R.drawable.location_marker));
myLocationStyle.strokeColor(Color.TRANSPARENT);// 設定圓形的邊框顔色
myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 設定圓形的填充顔色
myLocationStyle.strokeWidth(0.1f);// 設定圓形的邊框粗細
aMap.setMyLocationStyle(myLocationStyle);
aMap.setLocationSource(locationservice);//使用定位源的地方~~~~~~~~~~~~~~~~~~~~~~~~通過這個定位源就可以實時更細小藍點的位置了
aMap.setMyLocationEnabled(true);
getMapMode();
}
這個是我的主體Acitivity代碼:
public class MainMap extends Activity implements OnClickListener,
ServiceConnection {
private MapView mapView;
private AMap aMap;
private UiSettings mUiSettings;
private ImageButton btn_traffic_condition;
// private ImageButton btn_ride_navigation;
private boolean select = true;
private LocationService locationservice = null;
private PopupWindow mPopupWindow = null;
private PopupWindow PopupWindowlayer = null;
private View vPop = null;
private View vPop_layer = null;
private Button btn_clock;
private ImageButton btn_zoom_in, btn_zoom_out, btn_layer;// btn_box;
private Button btn_begin_record, btn_clear_route, btn_personel_record,
btn_cancel, btn_map_normal, btn_map_satellite, btn_map_3d,
btn_route;
private RelativeLayout startup;
private LinearLayout record_panel;
private TextView speedtext, timetext;
private float totaldistance = 0;
private float maxspeed = 0;
private boolean start = false;
private boolean change = false;
private boolean layselect = false;
private long lastClickTime = 0;
private long h, m, s, t;
// *************************綁定service相關操作*****************
private Intent ServiceIntent = null;
private double latitude = 0;
private double longitude = 0;
private double mlatitude = 0;
private double mlongitude = 0;
private double speed = 0;
private LatLng latlng;
private boolean closeinit = true;
private int mapmode = 0;
private DecimalFormat df = new DecimalFormat("#0.00");
private int duration = 0;
private VoiceService voice = null;
private String provider = null;
// *************************設定監聽器********************
private IntentFilter filter = new IntentFilter(
StaticData.LOCATION_DATA_BRODCAST_INTENT);
private BroadcastReceiver receiver = new BroadcastReceiver() {//broadcast reciver接收器相關的操作
@Override
public void onReceive(Context context, Intent intent) {
provider = intent.getStringExtra(StaticData.PROVIDER);
if (latitude != intent.getDoubleExtra(StaticData.LATITUDE, 0)
&& longitude != intent.getDoubleExtra(StaticData.LONGITUDE,
0)) {
if (start) {
latlng = new LatLng(latitude, longitude);
LatLng temp = new LatLng(intent.getDoubleExtra(
StaticData.LATITUDE, 0), intent.getDoubleExtra(
StaticData.LONGITUDE, 0));
float temp_distance = AMapUtils.calculateLineDistance(
latlng, temp);
if (provider.equals("lbs")) {
if (temp_distance <= 60) {
speed = temp_distance / 5 * 3.6;
totaldistance += temp_distance / 1000;
voice.playText("目前速度為" + df.format(speed) + "千米每小時");
} else {
speed = temp_distance / 5 * 3.6;
totaldistance += temp_distance / 1000;
voice.playText("目前速度為" + df.format(speed)
+ "千米每小時,速度有些過快");
}
} else if (provider.equals("gps")) {
speed = intent.getDoubleExtra(StaticData.SPEED, 0);
voice.playText("目前速度為" + df.format(speed) + "千米每小時");
}
if (speed >= maxspeed) {
maxspeed = (float) speed;
}
speedtext.setText("速度:" + df.format(speed) + "km/h");
DrawRideTrace(latlng, temp);
}
latitude = intent.getDoubleExtra(StaticData.LATITUDE, 0);
longitude = intent.getDoubleExtra(StaticData.LONGITUDE, 0);
}
if (start) {
t++;
h = t / 3600;
m = t % 3600 / 60;
s = t % 3600 % 60;
timetext.setText("時間:" + h + "h:" + m + "m:" + s + "s");
if (m == 10) {
voice.playText("您已經騎行" + df.format(totaldistance) + "千米");
}
}
mlatitude = intent.getDoubleExtra(StaticData.LATITUDE, 0);
mlongitude = intent.getDoubleExtra(StaticData.LONGITUDE, 0);
if (closeinit && locationservice != null) {
duration++;
setLocationIcon();
if (duration == 6) {
duration = 0;
closeinit = false;
startup.setVisibility(View.GONE);
}
}
}
};
// **********************電源管理機制****************************
private WakeLock wakeLock = null;
private void acquireWakeLock() {
if (wakeLock == null) {
System.out.println("Get lock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
System.out.println("Release LOCK");
wakeLock.release();
wakeLock = null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// R 需要引用包import com.amapv2.apis.R;
setContentView(R.layout.main_map);
mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState);// 必須要寫
init();
}
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
}
setVolumeControlStream(AudioManager.STREAM_MUSIC);// 設定聲音控制
initComponent();
setMapUi();
mstartService();
setTraffic();
getPopView();
getMaplayer();
}
private void mstartService() {
if (ServiceIntent == null) {
ServiceIntent = new Intent(MainMap.this, LocationService.class);
}
bindService(ServiceIntent, this, Context.BIND_AUTO_CREATE);
}
private void mstopService() {
unbindService(this);
ServiceIntent = null;
}
private void initComponent() {
startup = (RelativeLayout) findViewById(R.id.start_up_picture);
record_panel = (LinearLayout) findViewById(R.id.record_panel);
record_panel.setVisibility(View.GONE);
speedtext = (TextView) findViewById(R.id.speed_text);
timetext = (TextView) findViewById(R.id.time_text);
btn_traffic_condition = (ImageButton) findViewById(R.id.btn_traffic_condition);
btn_traffic_condition.setOnClickListener(this);
btn_clock = (Button) findViewById(R.id.btn_clock);
btn_clock.setOnClickListener(this);
btn_zoom_in = (ImageButton) findViewById(R.id.btn_zoom_in);
btn_zoom_in.setOnClickListener(this);
btn_zoom_out = (ImageButton) findViewById(R.id.btn_zoom_out);
btn_zoom_out.setOnClickListener(this);
btn_layer = (ImageButton) findViewById(R.id.btn_layer);
btn_layer.setOnClickListener(this);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
btn_cancel.setOnClickListener(this);
btn_cancel.setVisibility(View.GONE);
btn_route = (Button) findViewById(R.id.btn_route);
btn_route.setOnClickListener(this);
// btn_box = (ImageButton) findViewById(R.id.btn_box);
// btn_box.setOnClickListener(this);
}
// 配置mapUI界面
private void setMapUi() {
mUiSettings = aMap.getUiSettings();
mUiSettings.setMyLocationButtonEnabled(false);
mUiSettings.setZoomControlsEnabled(false);
mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
mUiSettings.setMyLocationButtonEnabled(false);// 設定預設定位按鈕是否顯示
// 設定定位的類型為定位模式 ,可以由定位、跟随或地圖根據面向方向旋轉幾種
}
private void setLocationIcon() {
// 自定義系統定位小藍點
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory
.fromResource(R.drawable.location_marker));
myLocationStyle.strokeColor(Color.TRANSPARENT);// 設定圓形的邊框顔色
myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 設定圓形的填充顔色
myLocationStyle.strokeWidth(0.1f);// 設定圓形的邊框粗細
aMap.setMyLocationStyle(myLocationStyle);
aMap.setLocationSource(locationservice);//設定定位源
aMap.setMyLocationEnabled(true);
getMapMode();
}
// 配置顯示道路情況的一些設定
private void setTraffic() {
MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
myTrafficStyle.setSeriousCongestedColor(0xff92000a);
myTrafficStyle.setCongestedColor(0xffea0312);
myTrafficStyle.setSlowColor(0xffff7508);
myTrafficStyle.setSmoothColor(0xff00a209);
aMap.setMyTrafficStyle(myTrafficStyle);
}
// ************************對于相關背景Service連接配接的操作*********************
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 取得location service執行個體
locationservice = ((LocationService.LocationServiceBinder) service)
.getLocationService();//擷取背景service内部變量的操作
voice = locationservice.getVoice();//擷取語音提示功能
// ClearSQL();
}
// 在service崩潰時觸發
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
// ********************************popupwindow初始化************************
private void getPopView() {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vPop = inflater.inflate(R.layout.clock_list_menu, null, false);
vPop.setFocusable(true);
vPop.setFocusableInTouchMode(true);
btn_begin_record = (Button) vPop.findViewById(R.id.btn_begin_record);
btn_begin_record.setOnClickListener(this);
btn_clear_route = (Button) vPop.findViewById(R.id.btn_clear_route);
btn_clear_route.setOnClickListener(this);
btn_personel_record = (Button) vPop
.findViewById(R.id.btn_personel_record);
btn_personel_record.setOnClickListener(this);
mPopupWindow = new PopupWindow(vPop, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, true);
mPopupWindow.setAnimationStyle(R.style.popupstyle);
mPopupWindow.setFocusable(true);
vPop.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mPopupWindow != null && mPopupWindow.isShowing()) {
change = false;
btn_clock.setVisibility(View.VISIBLE);
btn_cancel.setVisibility(View.GONE);
mPopupWindow.dismiss();
return true;
}
return false;
}
});
vPop.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mPopupWindow != null && mPopupWindow.isShowing()) {
change = false;
btn_clock.setVisibility(View.VISIBLE);
btn_cancel.setVisibility(View.GONE);
mPopupWindow.dismiss();
return true;
}
}
return false;
}
});
}
<span style="white-space:pre"> </span>//popupwindow相關的操作
private void getMaplayer() {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vPop_layer = inflater.inflate(R.layout.map_layer_popup, null, false);
vPop_layer.setFocusable(true);
vPop_layer.setFocusableInTouchMode(true);
btn_map_normal = (Button) vPop_layer.findViewById(R.id.btn_map_normal);
btn_map_normal.setOnClickListener(this);
btn_map_satellite = (Button) vPop_layer
.findViewById(R.id.btn_map_satellite);
btn_map_satellite.setOnClickListener(this);
btn_map_3d = (Button) vPop_layer.findViewById(R.id.btn_map_3d);
btn_map_3d.setOnClickListener(this);
PopupWindowlayer = new PopupWindow(vPop_layer,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
PopupWindowlayer.setAnimationStyle(R.style.maplayerstyle);
PopupWindowlayer.setFocusable(true);
vPop_layer.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (PopupWindowlayer != null && PopupWindowlayer.isShowing()) {
PopupWindowlayer.dismiss();
layselect = false;
btn_layer.setImageDrawable(getResources().getDrawable(
R.drawable.btn_layer_48));
return true;
}
return false;
}
});
vPop_layer.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (PopupWindowlayer != null
&& PopupWindowlayer.isShowing()) {
layselect = false;
btn_layer.setImageDrawable(getResources().getDrawable(
R.drawable.btn_layer_48));
PopupWindowlayer.dismiss();
return true;
}
}
return false;
}
});
}
// **************************按鍵監聽相關設定*****************************
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_layer:
PopupWindowlayer.showAsDropDown(btn_layer);
if (layselect == false) {
layselect = true;
btn_layer.setImageDrawable(getResources().getDrawable(
R.drawable.btn_cancel));
}
break;
case R.id.btn_traffic_condition:
if (select) {
ToastShow("實時路況已開啟");
btn_traffic_condition.setImageDrawable(getResources()
.getDrawable(R.drawable.main_roadcondition_on));
aMap.setTrafficEnabled(true);
select = false;
} else {
ToastShow("實時路況已關閉");
btn_traffic_condition.setImageDrawable(getResources()
.getDrawable(R.drawable.main_roadcondition_off));
aMap.setTrafficEnabled(false);
select = true;
}
break;
case R.id.btn_zoom_in:
aMap.moveCamera(CameraUpdateFactory.zoomIn());
break;
case R.id.btn_zoom_out:
aMap.moveCamera(CameraUpdateFactory.zoomOut());
break;
case R.id.btn_clock:
int cy = btn_clock.getHeight();
if (change == false) {
change = true;
btn_clock.setVisibility(View.GONE);
btn_cancel.setVisibility(View.VISIBLE);
}
mPopupWindow.showAtLocation(btn_clock, Gravity.BOTTOM
| Gravity.LEFT, 0, cy);
break;
case R.id.btn_route:
Intent pathsearch = new Intent();
Bundle bn = new Bundle();
if (mlatitude != 0 && mlongitude != 0) {
bn.putDouble(StaticData.MLATITUDE, mlatitude);
bn.putDouble(StaticData.MLONGITUDE, mlongitude);
} else {
ToastShow("現在無法進行路線查詢,請檢查網絡");
}
pathsearch.putExtras(bn);
pathsearch.setClass(MainMap.this, NavigationAty.class);
startActivityForResult(pathsearch, StaticData.REQUEST_PATH_SEARCH);
break;
// case R.id.btn_box:
// Intent off = new Intent(MainMap.this, OffLineMap.class);
// startActivity(off);
// break;
case R.id.btn_begin_record:
if (start == false) {
start = true;
btn_begin_record.setText("停止記錄");
record_panel.setVisibility(View.VISIBLE);
} else {
saveRelatedData();
start = false;
h = 0;
m = 0;
s = 0;
t = 0;
maxspeed = 0;
speed = 0;
totaldistance = 0;
btn_begin_record.setText("開始記錄");
record_panel.setVisibility(View.GONE);
}
break;
case R.id.btn_clear_route:
aMap.clear();
if (locationservice != null) {
setLocationIcon();
}
break;
case R.id.btn_personel_record:
if (start)
saveRelatedData();
Intent perIntent = new Intent();
perIntent.setClass(MainMap.this, PersonelAty.class);
startActivityForResult(perIntent, StaticData.REQUEST_PERSON_RECORD);
break;
case R.id.btn_map_normal:
selectMapLayer(R.id.btn_map_normal);
break;
case R.id.btn_map_satellite:
selectMapLayer(R.id.btn_map_satellite);
break;
case R.id.btn_map_3d:
selectMapLayer(R.id.btn_map_3d);
break;
}
}
private void getMapMode() {
SharedPreferences pref = getSharedPreferences(
StaticData.SMALL_DOG_PREFERENCE, 0);
int i;
i = pref.getInt(StaticData.MAP_MODE, 0);
switch (i) {
case 0:
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
aMap.setMapType(AMap.MAP_TYPE_NORMAL);
btn_map_normal.setBackgroundColor(getResources().getColor(
R.color.orange));
btn_map_satellite.setBackgroundColor(R.drawable.btn_background);
btn_map_3d.setBackgroundColor(R.drawable.btn_background);
break;
case 1:
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
btn_map_normal.setBackgroundColor(R.drawable.btn_background);
btn_map_satellite.setBackgroundColor(getResources().getColor(
R.color.orange));
btn_map_3d.setBackgroundColor(R.drawable.btn_background);
break;
case 2:
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
aMap.setMapType(AMap.MAP_TYPE_NORMAL);
btn_map_normal.setBackgroundColor(R.drawable.btn_background);
btn_map_satellite.setBackgroundColor(R.drawable.btn_background);
btn_map_3d.setBackgroundColor(getResources().getColor(
R.color.orange));
break;
}
}
<span style="white-space:pre"> </span>//對一些界面設定的可持久化
private void selectMapLayer(int i) {
SharedPreferences pref = getSharedPreferences(
StaticData.SMALL_DOG_PREFERENCE, 0);
Editor pref_editor = pref.edit();
switch (i) {
case R.id.btn_map_normal:
mapmode = 0;
pref_editor.putInt(StaticData.MAP_MODE, mapmode);
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
aMap.setMapType(AMap.MAP_TYPE_NORMAL);
btn_map_normal.setBackgroundColor(getResources().getColor(
R.color.orange));
btn_map_satellite.setBackgroundColor(R.drawable.btn_background);
btn_map_3d.setBackgroundColor(R.drawable.btn_background);
pref_editor.commit();
break;
case R.id.btn_map_satellite:
mapmode = 1;
pref_editor.putInt(StaticData.MAP_MODE, mapmode);
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
btn_map_normal.setBackgroundColor(R.drawable.btn_background);
btn_map_satellite.setBackgroundColor(getResources().getColor(
R.color.orange));
btn_map_3d.setBackgroundColor(R.drawable.btn_background);
pref_editor.commit();
break;
case R.id.btn_map_3d:
mapmode = 2;
pref_editor.putInt(StaticData.MAP_MODE, mapmode);
aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
aMap.setMapType(AMap.MAP_TYPE_NORMAL);
btn_map_normal.setBackgroundColor(R.drawable.btn_background);
btn_map_satellite.setBackgroundColor(R.drawable.btn_background);
btn_map_3d.setBackgroundColor(getResources().getColor(
R.color.orange));
pref_editor.commit();
break;
}
}
private void ToastShow(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
// *******************對後退按鍵的處理**********************
@Override
public void onBackPressed() {
if (lastClickTime <= 0) {
ToastShow("再按一次後退鍵退出應用");
lastClickTime = System.currentTimeMillis();
} else {
long currentClickTime = System.currentTimeMillis();
if (currentClickTime - lastClickTime < 1000) {
finish();
} else {
ToastShow("再按一次後退鍵退出應用");
lastClickTime = currentClickTime;
}
}
}
// ***********************生命周期處理*********************
@Override
protected void onResume() {
super.onResume();
acquireWakeLock();
registerReceiver(receiver, filter);
mapView.onResume();
}
@Override
protected void onPause() {
releaseWakeLock();
super.onPause();
mapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
System.out.println("onDestroy");
unregisterReceiver(receiver);
mstopService();
super.onDestroy();
mapView.onDestroy();
}
// **************************記錄軌迹函數**********************
private void DrawRideTrace(LatLng point1, LatLng point2) {
if (aMap != null) {
aMap.addPolyline((new PolylineOptions()).add(point1, point2)
.geodesic(false).color(R.color.blueviolet));
}
}
<span style="white-space:pre"> </span>//路徑規劃好之後相關畫線的操作
private void PlotBusRoute(LatLonPoint startpoint, LatLonPoint endpoint,
BusPath buspath) {
aMap.clear();// 清理地圖上的所有覆寫物
setLocationIcon();
BusRouteOverlay routeOverlay = new BusRouteOverlay(this, aMap, buspath,
startpoint, endpoint);
routeOverlay.removeFromMap();
routeOverlay.addToMap();
routeOverlay.zoomToSpan();
}
private void PlotCarRoute(LatLonPoint startpoint, LatLonPoint endpoint,
DrivePath drivepath) {
aMap.clear();// 清理地圖上的所有覆寫物
setLocationIcon();
DrivingRouteOverlay routeOverlay = new DrivingRouteOverlay(this, aMap,
drivepath, startpoint, endpoint);
routeOverlay.removeFromMap();
routeOverlay.addToMap();
routeOverlay.zoomToSpan();
}
private void PlotManRoute(LatLonPoint startpoint, LatLonPoint endpoint,
WalkPath walkpath) {
aMap.clear();// 清理地圖上的所有覆寫物
setLocationIcon();
WalkRouteOverlay routeOverlay = new WalkRouteOverlay(this, aMap,
walkpath, startpoint, endpoint);
routeOverlay.removeFromMap();
routeOverlay.addToMap();
routeOverlay.zoomToSpan();
}
<span style="white-space:pre"> </span>//這個是對跳轉activity相應的操作,作用完之後再主activity中進行畫線操作~~
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case StaticData.REQUEST_PATH_SEARCH:// 進行路線搜尋
if (data != null) {
Bundle re_Budle = data.getExtras();
if (re_Budle != null) {
double endpoint_latitude = re_Budle
.getDouble(StaticData.END_LATITUDE);
double endpoint_longitude = re_Budle
.getDouble(StaticData.END_LONGITUDE);
double startpoint_latitude = re_Budle
.getDouble(StaticData.START_LATITUDE);
double startpoint_longitude = re_Budle
.getDouble(StaticData.START_LONGITUDE);
LatLonPoint startpoint = new LatLonPoint(
startpoint_latitude, startpoint_longitude);
LatLonPoint endpoint = new LatLonPoint(endpoint_latitude,
endpoint_longitude);
switch (resultCode) {
case 0:
BusPath buspath = re_Budle
.getParcelable(StaticData.BUS_PATH);
PlotBusRoute(startpoint, endpoint, buspath);
break;
case 1:
DrivePath carpath = re_Budle
.getParcelable(StaticData.CAR_PATH);
PlotCarRoute(startpoint, endpoint, carpath);
break;
case 2:
WalkPath manpath = re_Budle
.getParcelable(StaticData.WALK_PATH);
PlotManRoute(startpoint, endpoint, manpath);
break;
}
}
}
}
}
<span style="white-space:pre"> </span>//這個是存儲一些常用變量的操作,由于參數較少,直接采用了sharedpreference的方式
private void saveRelatedData() {
SharedPreferences pre = getSharedPreferences(
StaticData.SMALL_DOG_PREFERENCE, 0);
Editor pre_edit = pre.edit();
pre_edit.putLong(StaticData.H, h);
pre_edit.putLong(StaticData.M, m);
pre_edit.putLong(StaticData.S, s);
pre_edit.putFloat(StaticData.TOTAL_DISTANCE, totaldistance);
pre_edit.putFloat(StaticData.MAX_SPEED, maxspeed);
pre_edit.commit();
}
}
如果無須看我講解或者等不了的小夥伴們請自行下載下傳我的源代碼~~~~
源代碼下載下傳------------>>猛戳這裡 點選打開連結