import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GPSTrackingService extends Service
{
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 0;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
public double lat1;
public double lat3;
public String id;
SimpleDateFormat sdf;
Intent intent;
int count = 0;
Context context;
String urladdress = "https://apidatabase.azurewebsites.net/api/Values/SendLocation";
CountDownTimer countDownTimer;
CountDownTimer countDownTimer1;
String value;
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
super.onCreate();
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
id = telephonyManager.getDeviceId();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
intent = new Intent(BROADCAST_ACTION);
context = this;
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(this);
final String strUserName = SP.getString("key_upload_quality", "15");
value = strUserName;
countDownTimer = new CountDownTimer(Long.valueOf(strUserName), 1000) {
@Override
public void onFinish() {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
countDownTimer.start();
}
@Override
public void onTick(long millisUntilFinished) {
if (strUserName != value) {
countDownTimer.start();
} else {
Log.d("Seconds"
, String.valueOf(millisUntilFinished));
}
}
};
countDownTimer.start();
}
@SuppressLint("MissingPermission")
@Override
public void onStart(Intent intent, int startId)
{
}
protected boolean isBetterLocation(Location location, Location currentBestLocation)
{
if (currentBestLocation == null)
{
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer)
{
return true;
// If the new location is more than two minutes older, it must be worse
}
else if (isSignificantlyOlder)
{
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate)
{
return true;
}
else if (isNewer && !isLessAccurate)
{
return true;
}
else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider)
{
return true;
}
return false;
}
/*
Checks whether two providers are the same
*/
private boolean isSameProvider(String provider1, String provider2)
{
if (provider1 == null)
{
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy()
{
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable)
{
final Thread t = new Thread()
{
@Override
public void run()
{
try
{
runnable.run();
}
finally
{
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener
{
@SuppressLint("MissingPermission")
public void onLocationChanged(final Location loc)
{
if (isBetterLocation(loc, previousBestLocation))
{
loc.getLatitude();
loc.getLongitude();
sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
Date date = new Date();
String myDate = sdf.format(date);
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
Log.d("Provider",loc.getProvider());
lat1 = loc.getLatitude();
lat3 = loc.getLongitude();
sendBroadcast(intent);
sendPost(myDate);
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle)
{
}
@Override
public void onProviderEnabled(String s)
{
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String s)
{
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
}
public void sendPost(final String myDate)
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("DeviceImei", id);
jsonParam.put("Latitude", lat1);
jsonParam.put("Longitude", lat3);
jsonParam.put("Distance", 0);
jsonParam.put("DateTime", myDate);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new
DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
locationManager.removeUpdates(listener);
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
MainActivity获取设置值。
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.Toast;
public class SettingsActivity extends AppCompactPreferenceActivity{
private static final String TAG = SettingsActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
PreferenceManager.setDefaultValues(this,R.xml.pref_main,false);
}
public static class MainPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(R.string.summary_choose_ringtone);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else if (preference instanceof EditTextPreference) {
if (preference.getKey().equals("key_gallery_name")) {
// update the changed gallery name to summary filed
preference.setSummary(stringValue);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
}
“设置”菜单,用于检测菜单中的任何更改
问题在于,当我单击不同的时间间隔时,如果用户单击,它将无法反映该值。只有当用户尝试重新启动该应用程序时,它才会设置为我指定的应用程序,但当用户检测到时间间隔已被用户更改时,我不希望它更改。