Android GPS定位记录发送功能

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

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

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

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


Android GPS定位记录发送功能_第1张图片


现在给出核心代码,感觉对于交流来说,实例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,开发)