Я пытаюсь установить уникальный идентификатор для телефона, но каждый раз, когда пользователь запускает кнопку, он генерирует новый идентификатор и отправляет его в базу данных. Приложение будет отслеживать местоположение пользователя, и я хотел бы установить идентификатор один раз, чтобы при каждом запуске отслеживания у пользователя всегда был один и тот же идентификатор. Прямо сейчас программа отправит идентификатор и будет оставаться неизменным при каждой отправке. Проблема, однако, возникает, когда пользователь возвращается к главному экрану и возвращается к экрану, чтобы начать отслеживание. Вот пример событий:
- Пользователь инициирует отслеживание
- Пользователь возвращается к главному экрану (оригинальный идентификатор утерян)
- Пользователь возвращается на экран с кнопкой, чтобы начать отслеживание
- Пользователь снова начинает отслеживание (генерируется новый идентификатор)
Я хотел бы сохранить идентификатор вместо создания нового каждый раз, когда пользователь инициирует отслеживание. Есть мысли о том, как это сделать? Вот код, который может помочь.
public class SendAlert extends Activity {
private Button help_button;
private TextView latitude;
private TextView longitude;
private TextView id;
Button sendButton;
EditText msgTextField;
String uuid = UUID.randomUUID().toString();
private LocationManager locManager;
private LocationListener locListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendalert);
SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE);
final String first = shared.getString("FIRSTNAME", "");
final String last = shared.getString("LASTNAME", "");
final long phone = shared.getLong("PHONE", 0);
final String city = shared.getString("CITY", "");
final int zip = shared.getInt("ZIP", 0);
help_button = (Button)findViewById(R.id.button1);
latitude = (TextView)findViewById(R.id.label_latitude);
longitude = (TextView)findViewById(R.id.label_longitude);
id = (TextView)findViewById(R.id.label_id);
help_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startLocation();
//id.setText(String.valueOf(uuid));
sendId(first, last, phone, city, zip);
}
});
}
private void startLocation()
{
//We get a reference to the LocationManager
locManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//We get the last known position
Location loc =
locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//We show the last known position
showPosition(loc);
//We checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location location) {
showPosition(location);
}
public void onProviderDisabled(String provider){
//labelState.setText("Provider OFF");
}
public void onProviderEnabled(String provider){
//labelState.setText("Provider ON ");
}
public void onStatusChanged(String provider, int status, Bundle extras){
//Log.i("", "Provider Status: " + status);
//labelState.setText("Provider Status: " + status);
}
};
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
private void showPosition(Location loc) {
if(loc != null)
{
latitude.setText(String.valueOf(loc.getLatitude()));
longitude.setText(String.valueOf(loc.getLongitude()));
id.setText(String.valueOf(uuid));
Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));
send(latitude);
}
else
{
latitude.setText("Latitude: No Data");
longitude.setText("Longitude: No Data");
}
}
private void send(View v)
{
// get the message from the message text box
//String msg = latitude.getText().toString() + "," + longitude.getText().toString(); s
String lat = latitude.getText().toString();
String lon = longitude.getText().toString();
// make sure the fields are not empty
//if (lat.length()>0)
if (lat != "0" && lon != "0")
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/receive.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat"
nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line
nameValuePairs.add(new BasicNameValuePair("id", uuid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
else
{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
}
private void sendId(String first, String last, long phone, String city, int zip)
{
// get the message from the message text box
String user_id = id.getText().toString();
// make sure the fields are not empty
//if (lat.length()>0)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/receive_user.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4
nameValuePairs.add(new BasicNameValuePair("id", user_id));
nameValuePairs.add(new BasicNameValuePair("firstname", first));
nameValuePairs.add(new BasicNameValuePair("lastname", last));
nameValuePairs.add(new BasicNameValuePair("phone", Long.toString(phone)));
nameValuePairs.add(new BasicNameValuePair("city", city));
nameValuePairs.add(new BasicNameValuePair("zip", Integer.toString(zip)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//msgTextField.setText(""); // clear text box
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}