Android GPS location record sending function

Write a blog to share experience and record the road of research and development.

Recently, I will write a small application for GPS positioning. The requirement is very simple. It can use the GPS hardware module of the Android phone to achieve positioning, and can record the positioning information, and can send it to the designated mailbox or QQ......

As shown in the figure below: Display positioning status. When the positioning is successful, the current position information can be recorded and notes can be added.

Record information in a simple Txt file format.




Now given the core code, I feel that the example dome is more popular with beginners for communication. If you need dome, leave your email address.

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 {


/**
* Define global location variables
*/
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;// Define the toggle button
String inputDistanceStr;// Input distance
// Location provided
String provider;
float[] result;


// Whether to read and write files
boolean isStarted = false;
boolean isStopped = false;
boolean isWrite = false;




// getting GPS status
boolean isGPSEnabled = false;


Button quit;


Button RecordTag;
Button SentEmail;
Button ClearTag;
// File read and write operations
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);
// Create storage file
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);


// Launch the program
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)); //Attachment file address
if (file.exists())
{

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("subject", file.getName());
intent.putExtra("body", "Henan Beidou Space Technology Co., Ltd. Positioning File Send-email sender"); //Body
//intent.putExtra()
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); //Add an attachment, the attachment is a file object
           if (file.getName().endsWith(".gz")) {
               intent.setType("application/x-gzip"); //If it is gz, use gzip mime
           } else if (file.getName().endsWith(".txt")) {
               intent.setType("text/plain"); //Plain text uses text/plain mime
           } else {
               intent.setType("application/octet-stream"); ​​//Others are sent using stream as binary data
           }
         startActivity(intent); //Call the mail client of the system to send*/
         
}else
{
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"No record file generated", Toast.LENGTH_LONG);
toast.show();
}

}


});





// Turn on location service and set location accuracy parameters
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 function is not turned on, or the positioning conditions are insufficient", Toast.LENGTH_LONG);
toast.show();
}





if (isOPen(BDgpsMainActivity.this,locationMangger))
{
LocationStan.setText("Positioning status: Positioning search star...");
}
else
{LocationStan.setText("Location Status: GPS is not turned on...");
openGPS(BDgpsMainActivity.this);
}



/**
 * Record current location information
 */
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,
"Current positioning is successful, it has been recorded!", Toast.LENGTH_SHORT);
  toast.show();
}
else
{
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"The current positioning conditions are insufficient, the recording failed!", Toast.LENGTH_SHORT);
  toast.show();

}

}else {
Toast toast = Toast.makeText(BDgpsMainActivity.this,
"Gps function is not turned on, or the positioning conditions are insufficient", 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("Location Status: Location Successful!");

currentLocation=location;//Record the current location
if (isStarted == true) {


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


stopLocation = location;
testDistance.setText("Tested distance: "
+ Float.toString(startLocation
.distanceTo(stopLocation)));
isStopped = false;
content.append("Tested distance: "
+ 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 converts latitude and longitude to distance each time you update, and calculates the change in distance between the two positions}
* */
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("Cannot get geographic information\r\n");
currentLocation=null;
}
Lat.setText("Lat: " + Double.toString(location.getLatitude()));
Lon.setText("Lon: " + Double.toString(location.getLongitude()));
distanceDiff.setText("distance change:" + Float.toString(dis));
LocationAccuracy.setText("Current accuracy: "
+ 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("Stop testing:\r\n");
isStopped = true;
isWrite = false;
}


public void startLoactionService() {


content.append("Start test:\r\n");
content.append(" "+" The actual distance entered: "+ 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("Exit prompt");  
   builder.setMessage("Whether to clear the location file when exiting");  
   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,
    "Cancel exit operation", Toast.LENGTH_LONG);
    toast.show();      
               
               }  
           });  
   
   
   return builder.create();  



/**
     * Judge whether GPS is turned on. If GPS or AGPS is turned on, it is considered to be turned on
     * @param context
     * @return true means to turn on
     */ 
    public final boolean isOPen(final Context context, LocationManager mlocationMangger) { 


        // Positioning via GPS , The positioning level can be accurate to the street (positioning through 24 satellites, positioning is accurate and fast in outdoor and open places) 
        boolean gps = mlocationMangger.isProviderEnabled(LocationManager.GPS_PROVIDER); 
        // Via WLAN or mobile network (3G/2G) Determined location (also called AGPS, assisted GPS positioning. Mainly used for positioning indoors or in densely covered places (buildings or dense forests, etc.) 
        //boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
        if (gps) { 
            return true; 
        } 
   
        return false; 
    }
    /**
     * Force users to turn on 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(); 
        } 
       
        
        
        
        
    }
    
    
    
}

///Remarks, the file operation class is used. No longer posted here


Guess you like

Origin blog.csdn.net/sun19890716/article/details/45844785