//从stackerflow本身获得此类软件包com.example.locationprovider;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
@Override
public void onLocationChanged(Location location)
{
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
//这是我的主要活动课。//我正在尝试制作一个应用程序,将用户的当前位置作为短信发送到//指定的号码。
package com.example.locationprovider;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements OnClickListener{
Button setNumberButton, shareLocationButton;
DataBaseHelper baseHelper = null;
Cursor cursor = null;
SQLiteDatabase database;
String num;
LocationManager lm;
String towers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setNumberButton = (Button) findViewById(R.id.setNumberButton);
shareLocationButton = (Button) findViewById(R.id.shareLocationButton);
setNumberButton.setOnClickListener(this);
shareLocationButton.setOnClickListener(this);
//Create Database here
baseHelper = new DataBaseHelper(this);
baseHelper.createDateBase();
//Opening database
database = baseHelper.openDataBase();
String col[] = {"number"};
//Getting the number from database
cursor = database.query("phoneNumber", col, null, null, null, null, null);
if(cursor.moveToFirst()){
//cursor was getting past values too.
//But now, only last value inserted will be used as a number.
while(cursor.moveToLast()){
num = cursor.getString(0);
//Showing current set number as a toast.
Toast.makeText(getBaseContext(), "Current number : " + num, Toast.LENGTH_LONG).show();
break;
}}
else
num = "";
}
@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
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public String getLocation(){
GPSTracker gpsTracker = new GPSTracker(this);
if(gpsTracker.canGetLocation()){
String stringLatitude = String.valueOf(gpsTracker.latitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
String country = gpsTracker.getCountryName(this);
String city = gpsTracker.getLocality(this);
String postalCode = gpsTracker.getPostalCode(this);
String addressLine = gpsTracker.getAddressLine(this);
return country;
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
String a = "No location";
return a;
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.setNumberButton://send to set number activity ..
Intent intent = new Intent(this, SetMessageNumber.class);
startActivity(intent);
break;
case R.id.shareLocationButton: //send message ..
String textMessage = getLocation(); //Text message to be sent
// Testing by creating a toast instead of sending text!
Toast.makeText(getBaseContext(), "Location :" + textMessage,Toast.LENGTH_LONG).show();
/*try {
//Making a SMS manager object
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, textMessage, null, null);
Toast.makeText(getApplicationContext(), "SMS sent",
Toast.LENGTH_LONG).show();
} catch(Exception e) {
Toast.makeText(getApplicationContext(),
"SMS failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }*/
break;
}
}
}
private String city,currentlocation,locality,country,zipcode;
GPSTracker gpstracker = new GPSTracker(getActivity(), 0);
// latitude and longitude
double latitude = gpstracker.getLatitude();
double longitude = gpstracker.getLongitude();
try {
geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
StringBuilder str = new StringBuilder();
if (geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
currentlocation = returnAddress.getAddressLine(0);
city = returnAddress.getAddressLine(1);
locality= localityString = returnAddress.getLocality();
country = returnAddress.getCountryName();
zipcode = returnAddress.getPostalCode();
} else {
Toast.makeText(getActivity(), "geocoder not present",
Toast.LENGTH_SHORT).show();
}
如果您想从手机连续更新,而不考虑手机是否移动,那么您所要做的就是将MIN_DISTANCE_CHANGE_FOR_UPDATES
和MIN_TIME_BW_UPDATES
的值都设置为0。
请注意,这样做是非常不鼓励的,因为这会对电池和其他资源提出很高的要求。
如果你只想一次性更新,只需使用以下方法:
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, pendingIntent);
有关此方面的更多详细信息:http://developer.android.com/reference/android/location/LocationManager.html