本代码实现GPS定位_第1页
本代码实现GPS定位_第2页
本代码实现GPS定位_第3页
本代码实现GPS定位_第4页
本代码实现GPS定位_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

本代码实现GPS定位,并定时在界面上呈现定位的精度以及在用卫星数量。

布局代码如下:

<LinearLayoutxmlns:android="/apk/res/android"

xmlns:tools="/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:id="@+id/showtv"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="GPS经纬度获取服务,每60秒界面更新一次数据,而后台GPS更新服务是每30秒更新一次GPS数据"/>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginTop="8dp"

android:gravity="center"

android:orientation="horizontal">

<Button

android:id="@+id/Startbtn"

android:layout_width="96dp"

android:layout_height="48dp"

android:text="@string/startbtn"/>

<Button

android:id="@+id/Stopbtn"

android:layout_width="96dp"

android:layout_height="48dp"

android:text="@string/stopbtn"/>

</LinearLayout>

<TextView

android:id="@+id/tv"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginLeft="4dp"

android:layout_marginTop="10dp"

android:text="@string/defaultshow"

android:textSize="18sp"/>

</LinearLayout>

首先写后台的LBSServiceListener实现LocationListener接口,在这个LBSServiceListener中可以重写方法,代码如下:

packagecom.exams.demo10_lbs;

importjava.text.DateFormat;

importjava.text.SimpleDateFormat;

importjava.util.Calendar;

importjava.util.GregorianCalendar;

importjava.util.TimeZone;

importandroid.location.Location;

importandroid.location.LocationListener;

importandroid.os.Bundle;

importandroid.util.Log;

publicclassLBSServiceListenerimplementsLocationListener{

publicintGPSCurrentStatus;

publicLocationcurrentLocation;

publicvoidonLocationChanged(Locationlocation){

//TODOAuto-generatedmethodstub

//-------

//Calledwhenanewlocationisfoundbythelocationprovider.

if(currentLocation!=null){

if(isBetterLocation(location,currentLocation)){

//Log.v("GPSTEST","It'sabetterlocation");

currentLocation=location;

}else{

//Log.v("GPSTEST","Notverygood!");

}

}else{

//Log.v("GPSTEST","It'sfirstlocation");

currentLocation=location;

}

}

//将数据通过get的方式发送到服务器,服务器可以根据这个数据进行跟踪用户的行走状态

privatevoiddoGet(Stringstring){

//TODOAuto-generatedmethodstub

//

}

publicvoidonProviderDisabled(Stringprovider){

//TODOAuto-generatedmethodstub

//if((LocationManager.NETWORK_PROVIDER).equals(provider)){

//locationManager.removeUpdates(this);

//}elseif((LocationManager.GPS_PROVIDER).equals(provider)){

//locationManager.removeUpdates(this);

//}

}

publicvoidonProviderEnabled(Stringprovider){

//TODOAuto-generatedmethodstub

}

publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){

//TODOAuto-generatedmethodstub

GPSCurrentStatus=status;

}

privatestaticfinalintCHECK_INTERVAL=1000*30;

protectedbooleanisBetterLocation(Locationlocation,

LocationcurrentBestLocation){

if(currentBestLocation==null){

//Anewlocationisalwaysbetterthannolocation

returntrue;

}

//Checkwhetherthenewlocationfixisnewerorolder

longtimeDelta=location.getTime()-currentBestLocation.getTime();

booleanisSignificantlyNewer=timeDelta>CHECK_INTERVAL;

booleanisSignificantlyOlder=timeDelta<-CHECK_INTERVAL;

booleanisNewer=timeDelta>0;

//Ifit'sbeenmorethantwominutessincethecurrentlocation,

//usethenewlocation

//becausetheuserhaslikelymoved

if(isSignificantlyNewer){

returntrue;

//Ifthenewlocationismorethantwominutesolder,itmust

//beworse

}elseif(isSignificantlyOlder){

returnfalse;

}

//Checkwhetherthenewlocationfixismoreorlessaccurate

intaccuracyDelta=(int)(location.getAccuracy()-currentBestLocation

.getAccuracy());

booleanisLessAccurate=accuracyDelta>0;

booleanisMoreAccurate=accuracyDelta<0;

booleanisSignificantlyLessAccurate=accuracyDelta>200;

//Checkiftheoldandnewlocationarefromthesameprovider

booleanisFromSameProvider=isSameProvider(location.getProvider(),

currentBestLocation.getProvider());

//Determinelocationqualityusingacombinationoftimelinessand

//accuracy

if(isMoreAccurate){

returntrue;

}elseif(isNewer&&!isLessAccurate){

returntrue;

}elseif(isNewer&&!isSignificantlyLessAccurate

&&isFromSameProvider){

returntrue;

}

returnfalse;

}

/**Checkswhethertwoprovidersarethesame*/

privatebooleanisSameProvider(Stringprovider1,Stringprovider2){

if(provider1==null){

returnprovider2==null;

}

returnprovider1.equals(provider2);

}

}

这样这个LBSServiceListener已经实现,其中我使用isBetterLocation()方法对Location做判断。

下面代码是GpsSatelliteListener实现GpsStatus.Listener:

packagecom.exams.demo10_lbs;

importandroid.location.GpsStatus;

importandroid.location.GpsStatus.Listener;

publicclassGpsSatelliteListenerimplementsListener{

publicvoidonGpsStatusChanged(intevent){

//TODOAuto-generatedmethodstub

switch(event){

//第一次定位

caseGpsStatus.GPS_EVENT_FIRST_FIX:

break;

//卫星状态改变

caseGpsStatus.GPS_EVENT_SATELLITE_STATUS:

break;

//定位启动

caseGpsStatus.GPS_EVENT_STARTED:

break;

//定位结束

caseGpsStatus.GPS_EVENT_STOPPED:

break;

}

}

}

重点是LBSService它是继承了Service.

在这个类中,重点通过onStartCommand方法和ACTIVITY沟通,实现将定位的经纬度等信息返回给activity的textview文本呈现出来。

packagecom.exams.demo10_lbs;

importjava.text.SimpleDateFormat;

importjava.util.Date;

importjava.util.Iterator;

importandroid.app.Notification;

importandroid.app.NotificationManager;

importandroid.app.PendingIntent;

importandroid.app.Service;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.content.IntentFilter;

importandroid.location.GpsSatellite;

importandroid.location.GpsStatus;

importandroid.location.Location;

importandroid.location.LocationListener;

importandroid.location.LocationManager;

importandroid.os.Binder;

importandroid.os.Bundle;

importandroid.os.IBinder;

importandroid.util.Log;

publicclassLBSServiceextendsService{

publicstaticfinalStringTAG="LBSService";

//30000ms--minimumtimeintervalbetweenlocationupdates,inmilliseconds

privatestaticfinallongminTime=30000;

//最小变更距离10m--minimumdistancebetweenlocationupdates,inmeters

privatestaticfinalfloatminDistance=10;

Stringtag=this.toString();

privateLocationManagerlocationManager;

privateLocationListenerlocationListener;

privateLocationlocation;

privateGpsStatusgStatus;

privateGpsSatelliteListenergpsSatelliteListener;

privatefinalIBindermBinder=newLBSServiceBinder();

privateNotificationManagermNM;

booleanflag;

CommandReceivercmdReceiver;

@Override

publicvoidonCreate(){

//TODOAuto-generatedmethodstub

flag=true;

cmdReceiver=newCommandReceiver();

super.onCreate();

mNM=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

showNotification();

startService();

Log.i(TAG,"inonCreatemethod.");

}

@Override

publicvoidonDestroy(){

//TODOAuto-generatedmethodstub

this.unregisterReceiver(cmdReceiver);//取消注册的CommandReceiver

super.onDestroy();

stopService();

mNM.cancel(R.string.lbsservice);

Log.i(TAG,"inonDestroymethod.");

}

@Override

publicIBinderonBind(Intentintent){

//TODOAuto-generatedmethodstub

returnmBinder;

}

@Override

publicintonStartCommand(Intentintent,intflags,intstartId){

//TODOAuto-generatedmethodstub

IntentFilterfilter=newIntentFilter();//创建IntentFilter对象

filter.addAction("com.exams.demo10_lbs.LBSService");

registerReceiver(cmdReceiver,filter);//注册Broadcast

//Receiver,后续会接收相关广播intent

doJob();//调用方法启动线程

returnsuper.onStartCommand(intent,flags,startId);

}

publicclassLBSServiceBinderextendsBinder{

LBSServicegetService(){

returnLBSService.this;

}

}

publicvoidstartService(){

locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

locationListener=newLBSServiceListener();

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,

minTime,minDistance,locationListener);

gpsSatelliteListener=newGpsSatelliteListener();

locationManager.addGpsStatusListener(gpsSatelliteListener);

Log.i(TAG,"instartServicemethod.");

}

publicvoidstopService(){

if(locationManager!=null&&locationListener!=null

&&gpsSatelliteListener!=null){

locationManager.removeUpdates(locationListener);

locationManager.removeGpsStatusListener(gpsSatelliteListener);

}

Log.i(TAG,"instopServicemethod.");

}

privateclassCommandReceiverextendsBroadcastReceiver{

@Override

publicvoidonReceive(Contextcontext,Intentintent){

//TODOAuto-generatedmethodstub

intcmd=intent.getIntExtra("cmd",-1);//获取Extra信息

if(cmd==MainActivity.CMD_STOP_SERVICE){//如果发来的消息是停止服务

flag=false;//停止线程

stopSelf();//停止服务

}

}//继承自BroadcastReceiver的子类

}

/***Showanotificationwhilethisserviceisrunning.*/

@SuppressWarnings("deprecation")

privatevoidshowNotification(){

//Inthissample,we'llusethesametext

//forthetickerandtheexpanded

//notification

CharSequencetext=getText(R.string.lbsservice);

//Settheicon,scrollingtextandtimestamp

Notificationnotification=newNotification(R.drawable.ic_launcher,

text,System.currentTimeMillis());

//ThePendingIntenttolaunchouractivityiftheuserselectsthis

Intentintent=newIntent(this,MainActivity.class);

//notification

PendingIntentcontentIntent=PendingIntent.getActivity(this,0,

intent,0);

//Settheinfofortheviewsthatshowinthenotificationpanel.

notification.setLatestEventInfo(this,"LBSService",

"LBSServicestarted",contentIntent);

//Sendthenotification.

//Weusealayoutidbecauseitisauniquenumber.Weuseitlaterto

//cancel.

mNM.notify(R.string.lbsservice,notification);

}

//方法:

publicvoiddoJob(){

newThread(){

publicvoidrun(){

while(flag){

try{//睡眠一段时间

Thread.sleep(60000);

}catch(Exceptione){

e.printStackTrace();

}

Intentintent=newIntent();//创建Intent对象

intent.setAction("com.exams.demo10_lbs");

location=locationManager

.getLastKnownLocation(LocationManager.GPS_PROVIDER);

gStatus=locationManager.getGpsStatus(null);

//获取默认最大卫星数

intmaxSatellites=gStatus.getMaxSatellites();

Iterable<GpsSatellite>iterable=gStatus.getSatellites();

Iterator<GpsSatellite>iterator=iterable.iterator();

intx=0;

while(iterator!=null&&iterator.hasNext()

&&x<=maxSatellites){

GpsSatellitegpsSatellite=(GpsSatellite)iterator

.next();

if(gpsSatellite.usedInFix())

x++;

}

Stringlatitude,longitude,accuracy,speed;

if(location!=null){

latitude=location.getLatitude()+"";

longitude=location.getLongitude()+"";

accuracy=location.getAccuracy()+"";

speed=location.getSpeed()+"";

}else{

latitude="0.0";

longitude="0.0";

accuracy="未知";

speed="0.0";

}

Bundlebundle=newBundle();

bundle.putString("latitude",latitude);

bundle.putString("longitude",longitude);

bundle.putString("accuracy",accuracy+"m");

bundle.putString("speed",speed+"m/s");

bundle.putString("Satenum",x+"个");

SimpleDateFormatsDateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");

DatenowDate=newDate();

StringdateString=sDateFormat.format(nowDate);

bundle.putString("date",

dateString+"");

intent.putExtras(bundle);

sendBroadcast(intent);//发送广播

}

}

}.start();

}

}

最后是Activity部分:

packagecom.exams.demo10_lbs;

importandroid.app.Activity;

importandroid.content.BroadcastReceiver;

importandroid.content.Context;

importandroid.content.Intent;

importandroid.content.IntentFilter;

importandroid.location.LocationManager;

importandroid.os.Bundle;

importvider.Settings;

importandroid.util.Log;

importandroid.view.Menu;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.TextView;

importandroid.widget.Toast;

publicclassMainActivityextendsActivity{

publicstaticfinalintCMD_STOP_SERVICE=0;

publicstaticfinalStringTAG="MainActivity";

publicButtonstartbtnButton,stopButton;

publicTextViewtView;

DataReceiverdataReceiver;//BroadcastReceiver对象

publicLocationManagerlManager;

@Override

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

startbtnButton=(Button)findViewById(R.id.Startbtn);

stopButton=(Button)findViewById(R.id.Stopbtn);

tView=(TextView)findViewById(R.id.tv);

lManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

//判断GPS是否正常启动

if(!lManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){

Toast.makeText(this,"请开启GPS导航...",Toast.LENGTH_SHORT).show();

//返回开启GPS导航设置界面

Intentintent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

startActivityForResult(intent,0);

return;

}

startbtnButton.setOnClickListener(newView.OnClickListener(){

publicvoidonClick(Viewv){

//TODOAuto-generatedmethodstub

startService();

}

});

stopButton.setOnClickListener(newView.OnClickListener(){

publicvoidonClick(Viewv){

//TODOAuto-generatedmethodstub

stopService();

}

});

}

privatevoidstartService(){

startbtnButton.setEnabled(false);

stopButton.setEnabled(true);

Intenti=newIntent(this,LBSService.class);

this.startService(i);

Log.i(TAG,"instartServicemethod.");

if(dataReceiver==null){

dataReceiver=newDataReceiver();

IntentFilterfilter=newIntentFilter();//创建IntentFilter对象

filter.addAction("com.exams.demo10_lbs");

registerReceiver(dataReceiver,filter);//注册BroadcastReceiver

}

}

privatevoidstopService(){

startbtnButton.setEnabled(true);

stopButton.setEnabled(false);

Intenti=newIntent(this,LBSService.class);

this.stopService(i);

Log.i(TAG,"instopServicemethod.");

if(dataReceiver!=null){

unregisterReceiver(dataReceiver);//取消注册BroadcastReceiver

dataReceiver=null;

}

}

@Override

publicbooleanonCreateOptionsMenu(Menumenu){

getMenuInflater().inflate(R.menu.activity_main,menu);

returntrue;

}

privateclassDataReceiverextendsBroadcastReceiver{//继承自BroadcastReceiver的子类

@Override

publicvoidonReceive(Contextcontext,Intentintent){//重写onReceive方法

Bundlebundledata=intent.getExtras();

if(bundledata!=null){

Stringlatitude=bundledata.getString("latitude");

Stringlongitude=bundledata.getString("longitude");

Stringaccuracy=bundledata.getString("accuracy");

Stringspeed=bundledata.getString("speed");

StringSatenum=bundledata.getSt

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论