一、学生定位签到页面
具体实现步骤:
1.1 高德地图申请key
1、创建新应用
进入高德地图api控制台,创建一个新应用。如果您之前已经创建过应用,可直接跳过这个步骤。
2、添加新Key
在创建的应用上点击"添加新Key"按钮,在弹出的对话框中,依次:输入应用名名称,选择绑定的服务为“Android平台SDK”,输入发布版安全码 SHA1、调试版安全码 SHA1、及 Package,如下图所示:
附:SHA1码的获取
1.2 实现高德地图自动定位---准备工作
1、下载jar包,导入jar包
首先去高德地图API官网下载好相关SDK jar文件,将下载的定位 SDK jar 文件复制到工程(此处截图以官方示例Demo为例子)的 libs 目录下,如果有老版本定位 jar 文件存在,请删除。
注:
- 第一个是2D地图的jar包,因为最后定位以后我要在地图上标出来位置
- 第二个是用于定位的jar包
对于每个jar文件,右键-选择Add As Library,导入到工程中。或者使用菜单栏 选择 File ->Project Structure->Modules-> Dependencies。点击绿色的加号选择File dependency. 然后选择要添加的jar包即可,此时build.gradle中会自动生成如下信息。
2、配置AndroidMainfest.xml文件
<!-- 申请必要的权限-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!--设置key-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="这里填写第一步你申请的那个key" />
<!--声明定位service-->
<service android:name="com.amap.api.location.APSService"></service>
</application>
AndroidMainfest.xml
3、Activity的布局文件
<com.amap.api.maps2d.MapView
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.amap.api.maps2d.MapView> <Button
android:id="@+id/requet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="签到"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
activity_main
4.
package com.cqvie.android_map; import android.content.DialogInterface;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
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.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.cqvie.options.HttpUtilsHttpURLConnection; import org.json.JSONException;
import org.json.JSONObject; import java.util.Date;
import java.util.HashMap;
import java.util.Map; public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener { private MapView mapView = null;
private AMap aMap;
private Button request;
private AMapLocationClient mLocationClient;
private AMapLocationClientOption mLocationOption;
private OnLocationChangedListener mListener;
//标识,用于判断是否只显示一次定位信息和用户重新定位
private boolean isFirstLoc = true;
String date=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //获取地图控件引用
mapView = (MapView) findViewById(R.id.map_view);
//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),实现地图生命周期管理
mapView.onCreate(savedInstanceState);
//获取签到按钮
request = (Button) findViewById(R.id.requet); init();
//初始化定位
mLocationClient = new AMapLocationClient(getApplicationContext());
mLocationClient.setLocationListener(this);
//初始化定位参数
mLocationOption = new AMapLocationClientOption();
// mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置是否返回地址信息(默认返回地址信息)
mLocationOption.setNeedAddress(true);
//设置是否只定位一次
mLocationOption.setOnceLocation(true);
//设置是否强制刷新WiFi
mLocationOption.setWifiScan(true);
//设置定位间隔,单位毫秒,默认为2000ms
//mLocationOption.setInterval(2000);
//给定位客户端对象设置定位参数
mLocationClient.setLocationOption(mLocationOption);
//启动定位
mLocationClient.startLocation();
} private void init() {
if (aMap == null) {
aMap = mapView.getMap();
UiSettings settings = aMap.getUiSettings();
aMap.setLocationSource(this);
settings.setMyLocationButtonEnabled(true);
aMap.setMyLocationEnabled(true);
}
} @Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mapView.onDestroy();
//mLocationClient.stopLocation();
mLocationClient.onDestroy();
} @Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理
mapView.onResume();
} @Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理
mapView.onPause();
} @Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),实现地图生命周期管理
mapView.onSaveInstanceState(outState);
} // @RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onLocationChanged(final AMapLocation aMapLocation) { if (aMapLocation!=null){
if (aMapLocation.getErrorCode()==0){
//定位成功回调信息,设置相关消息
aMapLocation.getLocationType();
aMapLocation.getLatitude();//获取纬度
aMapLocation.getLongitude();//获取经度
aMapLocation.getAccuracy();//获取精度信息
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
Date nowdate = new Date(aMapLocation.getTime());
date = df.format(nowdate);//定位时间
aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。
aMapLocation.getCountry();//国家信息
aMapLocation.getProvince();//省信息
aMapLocation.getCity();//城市信息
aMapLocation.getDistrict();//城区信息
aMapLocation.getStreet();//街道信息
aMapLocation.getStreetNum();//街道门牌号信息
//aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//aMapLocation.getAccuracy();//获取精度信息
aMapLocation.getPoiName();
aMapLocation.getAoiName(); //Log.d("why", String.valueOf(aMapLocation.getAoiName()));
// if (isFirstLoc){
//设置缩放级别
aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
//将地图移动到定位点
aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
//点击定位按钮 能够将地图的中心移动到定位点
mListener.onLocationChanged(aMapLocation);
//获取定位信息
final StringBuffer buffer = new StringBuffer();
buffer.append(aMapLocation.getCountry() + ""
//+ aMapLocation.getProvince() + ""
+ aMapLocation.getCity() + ""
// + aMapLocation.getProvince() + ""
+ aMapLocation.getDistrict() + ""
+ aMapLocation.getStreet() + ""
+ aMapLocation.getStreetNum()); Toast.makeText(getApplicationContext(), buffer.toString() + aMapLocation.getAoiName(), Toast.LENGTH_LONG).show();
//Log.d("tzk",buffer.toString()); isFirstLoc = false;
}
}
else {
Log.d("why", String.valueOf(aMapLocation.getErrorCode()));
//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
Log.e("AmapError", "location Error, ErrCode:"
+ aMapLocation.getErrorCode() + ", errInfo:"
+ aMapLocation.getErrorInfo());
Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
} request.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("签到")
.setMessage(date+ "\n" + aMapLocation.getAoiName())
.setPositiveButton("确定?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//新页面接收数据
Bundle bundle = MainActivity.this.getIntent().getExtras();
//接收name值
String name = bundle.getString("name");
//Toast.makeText(MainActivity.this,date,Toast.LENGTH_LONG).show();
signClickListen(date,name,aMapLocation.getAoiName()); }
})
.show();
}
});
} //激活定位
@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
mListener = onLocationChangedListener;
} @Override
public void deactivate() {
mListener = null;
} /**
* 签到点击事件
*/
public void signClickListen(final String date,final String name,final String signaddress) {
new Thread(new Runnable() {
@Override
public void run() {
String url = HttpUtilsHttpURLConnection.BASE_URL + "/SignServlet";
Map<String, String> params = new HashMap<String, String>();
Message msg = new Message();
Bundle data = new Bundle();
params.put("signtime",date);
params.put("name", name);
params.put("signaddress", signaddress);
String result = HttpUtilsHttpURLConnection.getContextByHttp(url, params);
msg.what = 0x12;
data.putString("result", result);
msg.setData(data);
hander.sendMessage(msg);
}
Handler hander = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x12) {
Bundle data = msg.getData();
String key = data.getString("result");//得到json返回的json
// Toast.makeText(MainActivity.this,key,Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(key);
String result = (String) json.get("result");
if ("success".equals(result)) {
Toast.makeText(MainActivity.this,name + "签到成功!", Toast.LENGTH_SHORT).show(); } else if ("error".equals(result)) {
Toast.makeText(MainActivity.this,name + "签到失败!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
}).start();
}
}
MainActivity