package me.covertness.moodmap;
import java.util.ArrayList; import java.util.List;
import android.app.Dialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.location.Location; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton;
import com.amap.api.cloud.model.AMapCloudException; import com.amap.api.cloud.model.CloudItem; import com.amap.api.cloud.model.CloudItemDetail; import com.amap.api.cloud.model.LatLonPoint; import com.amap.api.cloud.search.CloudResult; import com.amap.api.cloud.search.CloudSearch; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationListener; import com.amap.api.location.LocationManagerProxy; import com.amap.api.location.LocationProviderProxy; import com.amap.api.maps2d.AMap; import com.amap.api.maps2d.CameraUpdateFactory; import com.amap.api.maps2d.LocationSource; import com.amap.api.maps2d.MapView; import com.amap.api.maps2d.model.BitmapDescriptor; import com.amap.api.maps2d.model.BitmapDescriptorFactory; import com.amap.api.maps2d.model.LatLng; import com.amap.api.maps2d.model.LatLngBounds; import com.amap.api.maps2d.model.Marker; import com.amap.api.maps2d.model.MarkerOptions; import com.loopj.android.http.*; import org.apache.http.Header; import org.json.JSONException; import org.json.JSONObject;
public class extends ActionBarActivity implements LocationSource, AMapLocationListener, CloudSearch.OnCloudSearchListener { private String amapRestfulKey; private String cloudTableId; private MapView mapView; private AMap aMap; private LocationManagerProxy locationManagerProxy; private CloudSearch cloudSearch; private CloudSearch.Query currentQuery; private OnLocationChangedListener locationChangedListener; private AMapLocation currentLocation = null; private static AsyncHttpClient httpClient = new AsyncHttpClient();
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
try { ApplicationInfo app = this.getPackageManager().getApplicationInfo(this.getPackageName(),PackageManager.GET_META_DATA); amapRestfulKey = app.metaData.getString("me.covertness.moodmap.restful.apikey"); cloudTableId = app.metaData.getString("me.covertness.moodmap.cloud.tableid"); } catch (PackageManager.NameNotFoundException e) { Log.e("metadata", "Failed to load meta-data, NameNotFound: " e.getMessage()); } catch (NullPointerException e) { Log.e("metadata", "Failed to load meta-data, NullPointer: " e.getMessage()); }
mapView = (MapView) findViewById(R.id.map); mapView.onCreate(savedInstanceState);
if (aMap == null) { aMap = mapView.getMap(); aMap.setLocationSource(this); // 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false aMap.setMyLocationEnabled(true); }
cloudSearch = new CloudSearch(this); cloudSearch.setOnCloudSearchListener(this); }
protected void onDestroy() { super.onDestroy();
mapView.onDestroy(); }
protected void onPause() { super.onPause();
mapView.onPause(); }
protected void onResume() { super.onResume();
mapView.onResume(); }
protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState); }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; }
@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_settings) { return true; }
return super.onOptionsItemSelected(item); }
@Override public void activate(OnLocationChangedListener onLocationChangedListener) { locationChangedListener = onLocationChangedListener;
if (locationManagerProxy == null) { locationManagerProxy = LocationManagerProxy.getInstance(this); }
//此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, //注意设置合适的定位时间的间隔,并且在合适时间调用removeUpdates()方法来取消定位请求 //在定位结束后,在合适的生命周期调用destroy()方法 //其中如果间隔时间为-1,则定位只定一次 locationManagerProxy.requestLocationData( LocationProviderProxy.AMapNetwork, -1, 10, this); }
@Override public void deactivate() { locationChangedListener = null;
if (locationManagerProxy != null) { locationManagerProxy.removeUpdates(this); locationManagerProxy.destroy(); } locationManagerProxy = null; }
@Override public void onLocationChanged(AMapLocation aMapLocation) { if (locationChangedListener != null && aMapLocation != null) { int retCode = aMapLocation.getAMapException().getErrorCode(); if (retCode == 0) { currentLocation = aMapLocation; locationChangedListener.onLocationChanged(currentLocation);// 显示系统小蓝点 updateMapData(); showMoodDialog(); } else { Log.e("locate", aMapLocation.getAMapException().getErrorMessage()); } } }
/** * 此方法已经废弃 */ @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 onCloudSearched(CloudResult result, int rCode) { if (rCode == 0) { if (result != null && result.getQuery() != null) { if (result.getQuery().equals(currentQuery)) { //获取云数据 List<CloudItem> mCloudItems = result.getClouds(); if (mCloudItems != null && mCloudItems.size() > 0) { aMap.clear(); PoiOverlay mPoiCloudOverlay = new PoiOverlay(this, aMap, mCloudItems); mPoiCloudOverlay.removeFromMap(); mPoiCloudOverlay.addToMap(); mPoiCloudOverlay.zoomToSpan(); } else { Log.d("search", "result is empty"); } } } else { Log.d("search", "result is empty"); } } else { Log.e("search", "error code: " rCode); } }
@Override public void onCloudItemDetailSearched(CloudItemDetail cloudItemDetail, int i) {
}
private void showMoodDialog() { final Dialog moodDialog = new Dialog(this); moodDialog.setContentView(R.layout.choose_mood); moodDialog.setTitle(R.string.your_mood);
final JsonHttpResponseHandler publishMoodHandler = new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { try { if (response.getInt("status") == 1) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { updateMapData(); } }, 5000); } else { Log.e("publishMood", "failed: " response.getString("info")); } } catch (JSONException e) { e.printStackTrace(); } } };
final ImageButton happyButton = (ImageButton) moodDialog.findViewById(R.id.happyButton); // if button is clicked, close the custom dialog happyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moodDialog.dismiss(); publishMood(happyButton.getContentDescription().toString(), publishMoodHandler); } });
final ImageButton smileButton = (ImageButton) moodDialog.findViewById(R.id.smileButton); // if button is clicked, close the custom dialog smileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moodDialog.dismiss(); publishMood(smileButton.getContentDescription().toString(), publishMoodHandler); } });
final ImageButton sadButton = (ImageButton) moodDialog.findViewById(R.id.sadButton); // if button is clicked, close the custom dialog sadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moodDialog.dismiss(); publishMood(sadButton.getContentDescription().toString(), publishMoodHandler); } });
moodDialog.show(); }
private void publishMood(String mood, AsyncHttpResponseHandler responseHandler) { RequestParams params = new RequestParams(); params.put("key", amapRestfulKey); params.put("tableid", cloudTableId); params.put("loctype", "1");
JSONObject jsonObject = new JSONObject(); try { jsonObject.put("_name", mood); jsonObject.put("_location", currentLocation.getLongitude() "," currentLocation.getLatitude()); } catch (JSONException e) { e.printStackTrace(); } params.put("data", jsonObject.toString()); httpClient.post("http://yuntuapi.amap.com/datamanage/data/create", params, responseHandler); }
private void updateMapData() { //圆形查询范围 CloudSearch.SearchBound bound = new CloudSearch.SearchBound(new LatLonPoint( currentLocation.getLatitude(), currentLocation.getLongitude()), 50000); try { //构造查询对象 currentQuery = new CloudSearch.Query(cloudTableId, "", bound);
//异步搜索 cloudSearch.searchCloudAsyn(currentQuery); } catch (AMapCloudException e) { e.printStackTrace(); } } }
class PoiOverlay { private final List<CloudItem> mPois; private final AMap mAMap; private final Context mainContext; private ArrayList<Marker> mPoiMarks = new ArrayList<>();
public PoiOverlay(Context context, AMap amap, List<CloudItem> pois) { mainContext = context; mAMap = amap; mPois = pois; }
public void addToMap() { for (int i = 0; i < mPois.size(); i ) { Marker marker = mAMap.addMarker(getMarkerOptions(i)); marker.setObject(i); mPoiMarks.add(marker); } }
public void removeFromMap() { for (Marker mark : mPoiMarks) { mark.remove(); } }
public void zoomToSpan() { if (mPois != null && mPois.size() > 0) { if (mAMap == null) return; LatLngBounds bounds = getLatLngBounds(); mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20)); } }
private LatLngBounds getLatLngBounds() { LatLngBounds.Builder b = LatLngBounds.builder(); for (int i = 0; i < mPois.size(); i ) { b.include(new LatLng(mPois.get(i).getLatLonPoint().getLatitude(), mPois.get(i).getLatLonPoint().getLongitude())); } return b.build(); }
private MarkerOptions getMarkerOptions(int index) { return new MarkerOptions() .position( new LatLng(mPois.get(index).getLatLonPoint() .getLatitude(), mPois.get(index) .getLatLonPoint().getLongitude())) .title(getTitle(index)).snippet(getSnippet(index)) .icon(getBitmapDescriptor(index)); }
protected BitmapDescriptor getBitmapDescriptor(int index) { String title = mPois.get(index).getTitle(); if (title.equals(mainContext.getString(R.string.happy))) { return BitmapDescriptorFactory.fromResource(R.drawable.face_happy); } else if (title.equals(mainContext.getString(R.string.smile))) { return BitmapDescriptorFactory.fromResource(R.drawable.face_smile); } else if (title.equals(mainContext.getString(R.string.sad))) { return BitmapDescriptorFactory.fromResource(R.drawable.face_sad); } else { return null; } }
protected String getTitle(int index) { return mPois.get(index).getTitle(); }
protected String getSnippet(int index) { return mPois.get(index).getSnippet(); } }
|