Android:位置更新非常缓慢

loading...


0

我正在尝试创建一个应用程序,按下按钮向我的服务器发送我的Android设备的位置 . 不幸的是,位置更新非常缓慢,有时需要几分钟和几十米才能获得新位置 .

我对Android编程比较陌生,如果每次按下发送按钮,有人可以帮助我更新位置,我将不胜感激 .

import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

import org.json.*;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class DefaultActivity extends AppCompatActivity {
    private String serverURL;
    private TextView tv_Title, tv_Status;
    private Button b_SendLocation, b_SendNow, b_StopLocation;
    private User user;
    private FusedLocationProviderClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_default);
        Intent intent = getIntent();

        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
        locationClient = LocationServices.getFusedLocationProviderClient(this);

        serverURL = intent.getExtras().getString("serverURL");
        JSONParse(intent.getExtras().getString("myResponse"));

        tv_Title = findViewById(R.id.TextView_Title);
        tv_Status = findViewById(R.id.TextView_Status);
        b_SendLocation = findViewById(R.id.Button_SendLocation);
        b_SendNow = findViewById(R.id.Button_SendNow);
        b_StopLocation = findViewById(R.id.Button_StopLocation);

        tv_Title.setText(user.getLastName() + " " + user.getFirstName());
        tv_Status.setText(" ");

        b_SendLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Feedback("Sending location every 5 sec.");
            }

        });

        b_SendNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Feedback("Current location sent!");
                GetLocation();
            }

        });

        b_StopLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Feedback("Periodic sending halted!");
            }

        });
    }


    private void GetLocation() {
        if (ActivityCompat.checkSelfPermission(DefaultActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        locationClient.getLastLocation().addOnSuccessListener(DefaultActivity.this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if(location != null){
                    double latitude, longitude;
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    tv_Status.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
                    SendLocation(latitude, longitude);
                }
                else
                    tv_Status.setText("Location is null!");
            }
        });
    }

    private void SendLocation(double latitude, double longitude){
        OkHttpClient client = new OkHttpClient();
        String url = serverURL + "/api/user/?id=" + user.getID() + "&latitude=" + latitude + "&longitude=" + longitude;

        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e){
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_Status.append("\n\n Server error!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException{
                if (response.isSuccessful()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_Status.append("\n\n Server acknowledged!");
                        }
                    });
                }
            }
        });
    }

    private void JSONParse(String JSONString){
        User readUser = new User();
        try {
            JSONObject obj = new JSONObject(JSONString);

            readUser.setID(Integer.parseInt(obj.getString("ID")));
            readUser.setFirstName(obj.getString("FirstName"));
            readUser.setLastName(obj.getString("LastName"));
            readUser.setEmail(obj.getString("Email"));
            readUser.setPassword(obj.getString("Password"));
            readUser.setRole(obj.getString("Role"));

            Feedback("Welcome back " + readUser.getFirstName() + "!");
        } catch (JSONException e) {
            Feedback("JSON Exception!");
            e.printStackTrace();
        }

        user = readUser;
    }

    private void Feedback(String message){
        Toast toast=Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);
        toast.show();
    }
}

loading...

0回答

No Data

评论

暂时没有评论!