我想要保存位置的通知,在android,谷歌地图, 我的代码中的问题是当我保存远离当前位置的位置时,我想要在该特定保存位置弹出窗口,但是当我移动时,它会在当前位置给我弹出窗口...
这是我的项目的服务类......:
public class MyLocationService extends Service implements LocationListener{
//private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
SharedPrefs sharedPrefs;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
//private static final long MIN_TIME_BW_UPDATES = 1000 * 600 ; // 10 min
// Declaring a Location Manager
protected LocationManager locationManager;
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Location Changed", Toast.LENGTH_LONG).show();
DataSource ds = new DataSource(MyLocationService.this);
ds.open();
ArrayList<MLocation> locs = ds.getAllLocations();
ds.close();
if(locs!=null)
{
if(locs.size()>0)
{
ArrayList<Double>diffs = new ArrayList<Double>();
for(int i=0;i<locs.size();i++)
{
double latitude = Double.parseDouble(locs.get(i).getLatitude());
double longitude = Double.parseDouble(locs.get(i).getLongitude());
double dist = distance(latitude, longitude, location.getLatitude(), location.getLongitude(), 'K');
diffs.add(dist);
Log.i("GoogleMapsV2", i+" :"+dist);
}
//Collections.sort(diffs);
int minIndex = diffs.indexOf(Collections.min(diffs));
Toast.makeText(this, "You Are at "+locs.get(minIndex).getCategory(), Toast.LENGTH_SHORT).show();
Log.i("GoogleMapsV2" , " min:"+diffs.get(0));
String category = locs.get(minIndex).getCategory();
//changeRingerMode(category);
SharedPrefs sp = new SharedPrefs(this);
if(category.matches("Home"))
{
if(sp.getNotificationBoolean())
showNotification1(this, sharedPrefs.getToDoListHome());
if(sp.getProfileBoolean())
changeRingerMode(sharedPrefs.getProfileHome());
}
else if(category.matches("Work"))
{
if(sp.getProfileBoolean())
changeRingerMode(sharedPrefs.getProfileWork());
if(sp.getNotificationBoolean())
showNotification1(this, sharedPrefs.getToDoListWork());
}
else if(category.matches("Market"))
{
if(sp.getProfileBoolean())
changeRingerMode(sharedPrefs.getProfileMarket());
if(sp.getNotificationBoolean())
showNotification1(this,sharedPrefs.getToDoListMarket());
}
}
}
else
{
Toast.makeText(this, "Locs is Null", Toast.LENGTH_LONG).show();
}
}
void changeRingerMode(String ringerMode)
{
AudioManager am;
am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if(ringerMode.matches("Normal"))
{
Toast.makeText(getApplicationContext(), "Normal Mode Activated", Toast.LENGTH_LONG).show();
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else if(ringerMode.matches("Vibrate"))
{
Toast.makeText(getApplicationContext(), "Vibrate Mode Activated", Toast.LENGTH_LONG).show();
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
else if(ringerMode.matches("Silent"))
{
Toast.makeText(getApplicationContext(), "Silent Mode Activated", Toast.LENGTH_LONG).show();
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
else
{
Toast.makeText(getApplicationContext(), "Default:Normal Mode Activated", Toast.LENGTH_LONG).show();
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}
@SuppressLint("NewApi")
void showNotification(Context context, String todoList)
{
// new DrawGraph().showNotification();
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// intent triggered, you can add other intent for other actions
Intent intent1 = new Intent(context, Categories.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,intent1 , 0);
// this is it, we'll build the notification!
// in the addAction method, if you don't want any icon, just set the first param to 0
Notification mNotification = new Notification.Builder(context)
.setContentTitle("To Do")
.setContentText(todoList)
.setSmallIcon(R.drawable.ic)
.setContentIntent(pIntent)
.setSound(soundUri)
.build();
NotificationManager notificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);;
// If you want to hide the notification after it was selected, do the code below
// myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
void showNotification1(Context context, String todoList)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getApplicationContext());
/***
* Creating Alert Dialogue To show Categories
*/
// alertDialog.addContentView(listView, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
// alertDialog.add(input, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
alertDialog.setTitle("To Do");
alertDialog.setMessage(todoList);
alertDialog.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = alertDialog.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
}
/**
* distance Between Two latitudes and longitudes
* @param lat1
* @param lon1
* @param lat2
* @param lon2
* @param unit
* @return
*/
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, provider+" Enabled", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, provider+" Disabled", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Log.i("GoogleMapsV2" ,"Service Started");
sharedPrefs = new SharedPrefs(MyLocationService.this);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
getLocation();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public Location getLocation() {
try {
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Toast.makeText(this, "No Network Provider is Enabled", Toast.LENGTH_LONG).show();
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
0, //MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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,
0,this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
}
这些是SQLitehelper类:
public class DataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,MySQLiteHelper.COLUMN_DISCRIPTION, MySQLiteHelper.COLUMN_LATITUDE, MySQLiteHelper.COLUMN_LONGITUDE, MySQLiteHelper.COLUMN_CATEGORY };
public DataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void read() throws SQLException {
database = dbHelper.getReadableDatabase();
}
public MLocation createLocation(String latitude,String longitude,String discription, int category) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_LATITUDE, latitude);
values.put(MySQLiteHelper.COLUMN_LONGITUDE, longitude);
values.put(MySQLiteHelper.COLUMN_DISCRIPTION, discription);
values.put(MySQLiteHelper.COLUMN_CATEGORY, category);
long insertId = database.insert(MySQLiteHelper.TABLE_LOCATION, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
MLocation newMessage = cursorToLocation(cursor);
cursor.close();
return newMessage;
}
public void deleteLocation(MLocation loc) {
long id = loc.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_LOCATION, MySQLiteHelper.COLUMN_ID + " = " + id, null);
}
/**
* update a location
* @param location
*/
public void updateMessage(MLocation location) {
String q = "UPDATE "+MySQLiteHelper.TABLE_LOCATION+" SET "+
MySQLiteHelper.COLUMN_DISCRIPTION+" = '"+location.getDescription()
+"' WHERE "+MySQLiteHelper.COLUMN_ID+" = "+location.getId();
database.execSQL(q);
System.out.println("Rows Updated: " +q);
}
public ArrayList<MLocation> getAllLocations() {
ArrayList<MLocation> locs = new ArrayList<MLocation>();
try
{
Cursor cursor = database.query(MySQLiteHelper.TABLE_LOCATION,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
MLocation loc = cursorToLocation(cursor);
locs.add(loc);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return locs;
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
}
private MLocation cursorToLocation(Cursor cursor) {
MLocation loc = new MLocation();
loc.setId(cursor.getLong(0));
loc.setDescription(cursor.getString(1));
loc.setLatitude(cursor.getString(2));
loc.setLongitude(cursor.getString(3));
loc.setCategoryInt(cursor.getInt(4));
return loc;
}
}
和
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_LOCATION = "location";
public static final String COLUMN_ID = "id";
public static final String COLUMN_LATITUDE = "latitute";
public static final String COLUMN_LONGITUDE = "longitude";
public static final String COLUMN_DISCRIPTION = "discription";
public static final String COLUMN_CATEGORY = "category";
private static final String DATABASE_NAME = "profile.db";
private static final int DATABASE_VERSION = 2;
static final String DATABASE_CREATE = "create table "+TABLE_LOCATION+
"( " +COLUMN_ID+" integer primary key autoincrement,"+ COLUMN_LATITUDE+ " text not null,"+COLUMN_LONGITUDE+" text not null, "+COLUMN_DISCRIPTION +" text, "
+COLUMN_CATEGORY+" integer); ";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATION);
onCreate(db);
}
}