Android实现>>>普通GPS定位<<<并将坐标信息上传到数据库~

来源:互联网 发布:linux 安装luajit 编辑:程序博客网 时间:2024/04/30 15:20

       近期一个项目需要用到GPS和地图相关操作,因为以前没接触过,就在网上查了些内容,结合自己的需求,写了这么个小Demo,功能很简单,就是获取GPS坐标数据,并上传保存到数据库。(因为项目打算用百度地图,而百度的GPS坐标系跟实际的有比较大的差别,本来想直接在前台调用百度的批量坐标转换接口,但是这个方法在有大量坐标的时候貌似是一批一批转换,而不是一口气转完,不太好用,所以后来就用百度自己的定位SDK重新改造了一下,代码会在下一篇博文里发上来,这里先发获取原始GPS坐标的版本。)

先上包结构:



添加权限:这个权限是我在网上找的,如果仅仅是定位的话,可能不会全用到。

<!-- 这个权限用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 这个权限用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!-- 获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!-- 用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- 写入扩展存储,向扩展卡写入数据,用于写入离线定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- 访问网络,网络定位需要上网-->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- SD卡读取权限,用户写入离线定位数据-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--允许应用读取低级别的系统日志文件 -->
<uses-permission android:name="android.permission.READ_LOGS"/>

MainActivity:
package com.example.gpstest;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private Button startBtn;
private Button endBtn;
private Button endApp;
private TextView content;
private Intent intent;
private LocationReceiver lr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button) findViewById(R.id.startServBtn);
endBtn = (Button) findViewById(R.id.endServBtn);
endApp = (Button) findViewById(R.id.endApp);
content = (TextView) findViewById(R.id.content);
intent = new Intent(MainActivity.this, GpsService.class);
startBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startService(intent);
Toast.makeText(getApplicationContext(), "GPS测试开始", Toast.LENGTH_SHORT).show();
}
});
endBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
stopService(intent);
Toast.makeText(getApplicationContext(), "GPS测试结束", Toast.LENGTH_SHORT).show();
}
});
endApp.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
android.os.Process.killProcess(android.os.Process.myPid());
}
});
lr = new LocationReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("NEW LOCATION SENT");
registerReceiver(lr, intentFilter);
}

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

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(lr);
}

class LocationReceiver extends BroadcastReceiver {

String locationMsg = "";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
locationMsg = intent.getStringExtra("newLoca");
content.setText(locationMsg);
}
}
}

GpsService:
package com.example.gpstest;

import com.example.util.GpsServiceListener;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;

public class GpsService extends Service {

private static final long minTime = 2000;
private static final float minDistance = 10;
String tag = this.toString();
private LocationManager locationManager;
private LocationListener locationListener;
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GpsServiceListener(getApplicationContext());
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 
minTime, minDistance, locationListener);
Log.v(tag, "GpsService started");
}

@Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null && locationListener != null){
locationManager.removeUpdates(locationListener);
}
Log.v(tag, "GpsService ended");
}

@Override
public IBinder onBind(Intent arg0) {

return null;
}
}
 
GpsServiceListener: 
package com.example.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;

public class GpsServiceListener implements LocationListener {


private Context context;
private static final String tag = "GPSSERVICELISTENER";
private static final float minAccuracyMeters = 35;
public int gpsCurrentStatus;

public GpsServiceListener(){
super();
}
public GpsServiceListener(Context context){
super();
this.context = context;
}
@Override
public void onLocationChanged(Location location) {

if(location != null){
if(location.hasAccuracy() && location.getAccuracy() <= minAccuracyMeters){
//获取参数,并post到服务器端
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer sb = new StringBuffer();
sb.append("经度=").append(location.getLongitude());
sb.append("\n纬度=").append(location.getLatitude());
sb.append("\n时间=").append(sdf.format(new Date()));
sendToActivity(sb.toString());
Log.v(tag, sb.toString());

try {
Map<String,String> map = new HashMap<String, String>();
map.put("longi", location.getLongitude()+"");
map.put("lati", location.getLatitude()+"");
map.put("time", sdf.format(new Date()));
String url = HttpUtil.BASE_URL+"coords.do?method=addCoords";
HttpUtil.postRequest(url, map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

//发送广播,提示更新界面
private void sendToActivity(String str){
Intent intent = new Intent();
intent.putExtra("newLoca", str);
intent.setAction("NEW LOCATION SENT");
context.sendBroadcast(intent);
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
gpsCurrentStatus = status;
}
}
 
HttpUtil:
package com.example.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

//创建HttpClient对象
public static HttpClient httpClient = new DefaultHttpClient();
public static final String BASE_URL = "http://88.88.88.88:8888/gps/";
public static String getRequest(final String url) throws Exception{

FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
// 创建HttpGet对象
HttpGet get = new HttpGet(url);
//发送get请求
HttpResponse httpResponse = httpClient.execute(get);
//如果服务器成功地返回响应
if(httpResponse.getStatusLine().getStatusCode() == 200){
//获取服务器响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}
public static String postRequest(final String url,
final Map<String,String> rawParams) throws Exception{

FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
// 创建HttpPost对象
HttpPost post = new HttpPost(url);
//如果传递的参数个数比较多,可以对传递的参数进行封装
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(String key:rawParams.keySet()){
//封装请求参数
params.add(new BasicNameValuePair(key, rawParams.get(key)));
}
//设置请求参数
post.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
//发送post请求
HttpResponse httpResponse = httpClient.execute(post);
//如果服务器成功地返回响应
if(httpResponse.getStatusLine().getStatusCode() == 200){
//获取服务器响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return null;
}
});
new Thread(task).start();
return task.get();
}
}

0 0
原创粉丝点击