写博客分享经验,记录研发之路。

最近,要写一个GPS定位的小应用。要求很简单,能够利用Android 手机的GPS硬件模块实现定位,并能记录定位信息,并能发送给指定的邮箱或QQ……

如下图所示:显示定位状态。定位成功的情况下,可以记录当前位置信息,并能添加备注。

记录信息,采用简单的Txt文件格式。

现在给出核心代码,感觉对于交流来说,实例dome更受初学者喜欢。如果需要dome,留下邮箱地址。

package com.example.bd_gpssender;

import java.io.File;
import java.io.IOException;

import com.filerw.help.FileHelper;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class BDgpsMainActivity extends Activity {

/**
* 定义全局位置变量
*/
private Location PreLocation;
private Location currentLocation=null;
private Location startLocation;
private Location stopLocation;

private LocationManager locationMangger;

private TextView testDistance, Lat, Lon, distanceDiff, LocationAccuracy,LocationStan;

private EditText inputDistance;

private ToggleButton Bend;// 定义切换按钮
String inputDistanceStr;// 输入距离
// 位置提供
String provider;
float[] result;

// 是否进行读写文件操作
boolean isStarted = false;
boolean isStopped = false;
boolean isWrite = false;

// getting GPS status
boolean isGPSEnabled = false;

Button quit;

Button RecordTag;
Button SentEmail;
Button ClearTag;
// 文件读写操作
private FileHelper filehelper;

private String fileName,RecordfileName;

private StringBuilder content = new StringBuilder();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bdgps_main);
// 创建存储文件
fileName = "BDgpsSender.txt";
RecordfileName="BDrecordTag.txt";
filehelper = new FileHelper(this.getApplicationContext());
try {
filehelper.createSDFile(fileName);

} catch (IOException e) {
e.printStackTrace();
}

try {
filehelper.createSDFile(RecordfileName);

} catch (IOException e) {
e.printStackTrace();
}
LocationStan=(TextView)this.findViewById(R.id.LocationStan);
testDistance = (TextView) this.findViewById(R.id.TestDistance);
Lat = (TextView) this.findViewById(R.id.FromLL);
Lon = (TextView) this.findViewById(R.id.ToLL);
distanceDiff = (TextView) this.findViewById(R.id.DistanceDiff);
inputDistance = (EditText) this.findViewById(R.id.InputDistance);
Bend = (ToggleButton) this.findViewById(R.id.BS);
LocationAccuracy = (TextView) this.findViewById(R.id.LocationAccuracy);
inputDistanceStr = inputDistance.getText().toString();
quit = (Button) this.findViewById(R.id.button1);
RecordTag=(Button)this.findViewById(R.id.btnRecord);
SentEmail=(Button)this.findViewById(R.id.btnSentEmail);
ClearTag=(Button)this.findViewById(R.id.btnClearRecord);

// 推出程序
quit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

ExitDialog(BDgpsMainActivity.this).show();

}

});
ClearTag.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
inputDistance.setText(null);
}

});

SentEmail.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
File file = new File( filehelper.getEmailfilepath(RecordfileName)); //附件文件地址
if (file.exists())
{

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("subject", file.getName());
intent.putExtra("body", "河南北斗空间科技有限公司定位文件发送 - email sender"); //正文
//intent.putExtra()
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); //添加附件,附件为file对象
           if (file.getName().endsWith(".gz")) {
               intent.setType("application/x-gzip"); //如果是gz使用gzip的mime
           } else if (file.getName().endsWith(".txt")) {
               intent.setType("text/plain"); //纯文本则用text/plain的mime
           } else {
               intent.setType("application/octet-stream"); //其他的均使用流当做二进制数据来发送
           }
         startActivity(intent); //调用系统的mail客户端进行发送*/
         
}else
{
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"未产生记录文件", Toast.LENGTH_LONG);
toast.show();
}

}

});

// 开启定位服务设置定位精度参数
String serviceName = Context.LOCATION_SERVICE;
locationMangger = (LocationManager) getSystemService(serviceName);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(true);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_HIGH);

provider = locationMangger.getBestProvider(criteria, true);
if (provider != null) {
locationMangger.requestLocationUpdates(provider, 0, 0,
locationListener);
} else {
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"Gps功能未开启,或定位条件不足", Toast.LENGTH_LONG);
toast.show();
}

if (isOPen(BDgpsMainActivity.this,locationMangger))
{
LocationStan.setText("定位状态: 正在定位搜星...");
}
else
{LocationStan.setText("定位状态: 未开启GPS...");
openGPS(BDgpsMainActivity.this);
}

/**
 * 记录当前位置信息
 */
RecordTag.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

if (provider != null) {
if (currentLocation!=null)
{
inputDistanceStr = inputDistance.getText().toString();
Time timer=new Time();
timer.setToNow();
String writercontent=" Location:\r\n" + " Lat: "
+ Double.toString(currentLocation.getLatitude()) + "\r\n"
+ " Lon: " + Double.toString(currentLocation.getLongitude())
+ "\r\n" + " Altitude: " + Double.toString(currentLocation.getAltitude())
+ "\r\n"
+ " CurAcury: " + Float.toString(currentLocation.getAccuracy())
+ "\r\n" + " CurTime: " + timer.year+"-"+timer.month+"-"+timer.monthDay+" "+timer.hour+":"+timer.minute+":"+timer.second
+ "\r\n" +"Tag: "+ inputDistanceStr+"\r\n"+"\r\n";

filehelper.writeFileData(RecordfileName, writercontent);
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"当前定位成功,已记录!", Toast.LENGTH_SHORT);
  toast.show();
}
else
{
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"当前定位条件不足,记录失败!", Toast.LENGTH_SHORT);
  toast.show();

}

}else {
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"Gps功能未开启,或定位条件不足", Toast.LENGTH_LONG);
toast.show();
}
}

});

}

protected void onResume() {
super.onResume();

Bend.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

if (isChecked) {
startLoactionService();
}
else{
stopLocationService();
}

}

});

}

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

private final LocationListener locationListener = new LocationListener() {

public void onLocationChanged(Location location) {

if (location != null) {
LocationStan.setText("定位状态: 定位成功!");

currentLocation=location;//记录当前的位置
if (isStarted == true) {

startLocation = location;
isStarted = false;
} else if (isStopped == true) {

stopLocation = location;
testDistance.setText("测试出的距离: "
+ Float.toString(startLocation
.distanceTo(stopLocation)));
isStopped = false;
content.append(" 测试出的距离: "
+ Float.toString(startLocation
.distanceTo(stopLocation)) + "\r\n");

}
}

updateWithNewLocation(location);
}

public void onProviderDisabled(String provider) {

updateWithNewLocation(null);

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}
};

/**
* @param Location
* @return null {@literal 每次更新经纬度转换为距离,并计算出两次位置之间的距离变化}
* */
private void updateWithNewLocation(Location location) {

float dis = (float) 0.000;
if (location != null) {
if (PreLocation != null) {
dis = PreLocation.distanceTo(location);
}
PreLocation = location;
} else {
distanceDiff.setText("无法获取地理信息\r\n");
currentLocation=null;
}
Lat.setText("Lat: " + Double.toString(location.getLatitude()));
Lon.setText("Lon: " + Double.toString(location.getLongitude()));
distanceDiff.setText("距离变化:" + Float.toString(dis));
LocationAccuracy.setText("当前精度: "
+ Float.toString(location.getAccuracy()));
if (isWrite) {
//SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.getDefault()); 
content.append(" Location:\r\n" + " Lat: "
+ Double.toString(location.getLatitude()) + "\r\n"
+ " Lon: " + Double.toString(location.getLongitude())
+ "\r\n" +  " Altitude: " + Double.toString(currentLocation.getAltitude())
+ "\r\n"+ " CurAcury: " + Float.toString(currentLocation.getAccuracy())
                    + "\r\n" + "DistenceChange: " + Float.toString(dis) 
+ "\r\n" + " CurrentTime: " + location.getTime()
+ "\r\n"
);
filehelper.writeFileData(fileName, content.toString());
content.delete(1, content.length());
isStopped = false;

}
}
public float getDistanceDiff(float inputDistance, float testDistance)
   {
   
float distanceDiff = (float) 0.0;
if (inputDistance != 0)
{
   distanceDiff = Math
   .abs(((testDistance - inputDistance) / inputDistance));
}
return distanceDiff;

}
public void stopLocationService() {

content.append(" 停止测试:\r\n");
isStopped = true;
isWrite = false;
}

public void startLoactionService() {

content.append(" 开始测试:\r\n ");
content.append(" " + " 输入的实际距离: " + inputDistance.getText().toString()
+ " \r\n");
isStarted = true;
isWrite = true;

}

private Dialog ExitDialog(Context context) {  
   AlertDialog.Builder builder = new AlertDialog.Builder(context);  
   builder.setIcon(R.drawable.ic_launcher);  
   builder.setTitle("退出提示");  
   builder.setMessage("退出时是否清除定位文件");  
   builder.setPositiveButton("清除",  
           new DialogInterface.OnClickListener() {  
               public void onClick(DialogInterface dialog, int whichButton) {           
                filehelper.deleteSDFile(RecordfileName);
    filehelper.deleteSDFile(fileName);
   
    BDgpsMainActivity.this.locationMangger
    .removeUpdates(locationListener);
           BDgpsMainActivity.this.finish();
               }  
           });  
   builder.setNegativeButton("保留",  
           new DialogInterface.OnClickListener() {  
               public void onClick(DialogInterface dialog, int whichButton) {  
               
                BDgpsMainActivity.this.locationMangger
    .removeUpdates(locationListener);
           BDgpsMainActivity.this.finish();    
               
               }  
           });  
   builder.setNeutralButton("取消",  new DialogInterface.OnClickListener() {  
               public void onClick(DialogInterface dialog, int whichButton) {  
               
                Toast toast = Toast.makeText(BDgpsMainActivity.this,
    "取消退出操作", Toast.LENGTH_LONG);
    toast.show();      
               
               }  
           });  
   
   
   return builder.create();  
}

/**
     * 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */ 
    public final boolean isOPen(final Context context,LocationManager mlocationMangger) {

// 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快) 
        boolean gps = mlocationMangger.isProviderEnabled(LocationManager.GPS_PROVIDER); 
        // 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位) 
        //boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
        if (gps) { 
            return true; 
        } 
   
        return false; 
    }
    /**
     * 强制帮用户打开GPS
     * @param context
     */ 
    public final void openGPS(Context context) { 
        Intent GPSIntent = new Intent(); 
        GPSIntent.setClassName("com.android.settings", 
                "com.android.settings.widget.SettingsAppWidgetProvider"); 
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE"); 
        GPSIntent.setData(Uri.parse("custom:3")); 
        try { 
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send(); 
        } catch (CanceledException e) { 
            e.printStackTrace(); 
        } 
       
        
        
        
        
    }
    
    
    
}

///备注,其中用到文件操作类。这里不再贴出

Android GPS定位记录发送功能相关推荐

  1. android GPS 定位

    转自:http://blog.csdn.net/u013686019/article/details/47444839 Android:V4.2.2 Source Insight 写在前面 在漫长的A ...

  2. gps定位c语言开发,Android GPS定位开发教程

    要获取精确的位置服务信息需要 GPS 硬件的支持.在应用程序开发阶段,由于模拟器中并没有真正的 GPS 硬件,因此不能获得真实的 GPS 信息.但是可以使用 Eclipse 视图模式的 DDMS 模式 ...

  3. android 汽车gps开发,Android GPS定位开发教程

    要获取精确的位置服务信息需要 GPS 硬件的支持.在应用程序开发阶段,由于模拟器中并没有真正的 GPS 硬件,因此不能获得真实的 GPS 信息.但是可以使用 Eclipse 视图模式的 DDMS 模式 ...

  4. android gps定位完整代码,android GPS定位 (完整代码实例)

    [实例简介] android平台上完成GPS定位功能,完整代码实例,多次测试. [实例截图] [核心代码] GPStest └── GPStest ├── AndroidManifest.xml ├─ ...

  5. Android GPS定位及实例

    使用GPS 定位,首先,需要在清单文件(AndroidManifest.xml)中注册获取定位的权限: 1.获取位置管理器对象LocationManager import android.locati ...

  6. android 模拟gps坐标,1020. Android GPS定位欺骗(模拟定位)的3类途径4种方式

    前段时间发布的手游PokemonGo相信大家都有耳闻,而因为这个游戏在国内的坐标遭到了封锁,很多科学游戏方法也陆续涌现.好不热闹. 那其实,PokemonGo最初的版本,在大陆是可以通过简单的vpn+ ...

  7. android gps定位工具类,Android原生GPS和网络定位工具类

    在应用开发中我们常常需要网络获取位置的方法,这里做一个工具类的封装,使用的是Android原生定位,包含两种方式,一种是原生GPS一种是网络定位的封装实现: 工具类代码如下所示: package co ...

  8. Android GPS定位 取得城市名称

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 转自:h ...

  9. android 定位服务源码,android gps定位app源码(GpsTracker)

    [实例简介]做到了 gps 开启关闭后的提醒 以及地理位置记录(经纬度) [实例截图] [核心代码] package android.gpstracker; import android.app.Ac ...

最新文章

  1. python装饰器原理-python装饰器原理和用法总结
  2. 大型网站演化发展历程之二
  3. C++利用访函数进行选择排序
  4. 链表定义、链表的插入、链表的删除、链表的查找
  5. android环境搭建出错,androidstudio配置环境遇到的各种错误(持续更新中)
  6. 在一个Java版本上运行Eclipse IDE,但在另一个Java版本上运行
  7. telephone 为空 唯一索引_PostgreSQL的空串、空值对唯一性约束的影响
  8. React开发(107):回显数据直接getFieldDecorator定义
  9. pytest测试实战 电子书_电子书丨Selenium 3+Python 3自动化测试项目实战:从菜鸟到高手...
  10. 关于字符串截取的函数
  11. LeetCode-94. 二叉树的中序遍历
  12. android 性能优化---(5)Bitmap图片资源优化
  13. 蓝桥杯 BASIC-2 基础练习 01字串
  14. [转载]java中try 与catch的使用
  15. weblogic系列漏洞整理 -- 3. weblogic 后台提权
  16. 04 grep正则表达式与shellscipt脚本编程
  17. 从源码角度深入理解LayoutInflater
  18. FreeRTOS中的 ’上下文切换‘ 含义
  19. VB中关于Array函数与Split函数
  20. 27 信息过滤与反垃圾

热门文章

  1. 数据分析:在天猫开一个店需要多少成本?
  2. DSP在SYS/BIOS下串口(UART)接收之环形队列
  3. Git 分支篇之远程分支
  4. Html5 学习笔记 【PC固定布局】 实战7 风景欣赏 联系我们
  5. SSMS错误代码大全
  6. 识破面试官的套路:十个典型的面试问题剖析
  7. 软件工程专业期末项目开发全流程模拟日志(第一天)
  8. python 请假审批系统_菜鸟也要懂点设计模式|用Python设计一个请假模式
  9. Android打开QQ临时会话和打开群聊
  10. 大学两年时间的一些感悟