Я новичок в Android, поэтому, пожалуйста, прости меня, если эта самая основная ошибка, но я пробую ее в течение 3 дней, но не могу найти решение.
Я просто пытаюсь определить местоположение пользователя через GPS.
MainActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
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.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
public class MainActivity extends AppCompatActivity {
//Variables
TextView lat, lng;
Button start, stop;
//Location
private FusedLocationProviderClient fusedLocationProviderClient;
private final static int FINE_LOCATION_REQUEST_CODE = 1000;
LocationRequest locationRequest;
LocationCallback locationCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializevar();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
lat = (TextView)findViewById(R.id.lat);
lng = (TextView)findViewById(R.id.lng);
start = (Button)findViewById(R.id.begin);
stop = (Button)findViewById(R.id.stop);
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_REQUEST_CODE);
Toast.makeText(this,"Reopen Apps",Toast.LENGTH_LONG);
}
else {
buildlocationrequest();
buildlocationcallback();
//create fused provider client
fusedLocationProviderClient = LocationServices. getFusedLocationProviderClient(this);
stop.setEnabled(false);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
return;
}
String latt = "Fetching";
String lngt = "Data";
lat.setText(latt);
lng.setText(lngt);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
start.setEnabled(!start.isEnabled());
stop.setEnabled(!stop.isEnabled());
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_REQUEST_CODE);
return;
}
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
start.setEnabled(!start.isEnabled());
stop.setEnabled(!stop.isEnabled());
}
});
}
}
private void buildlocationcallback() {
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for(Location location:locationResult.getLocations())
{
//location mil gaya
String latt = "Latitude" + location.getLatitude();
String lngt = "Longitude" + location.getLongitude();
lat.setText(latt);
lng.setText(lngt);
}
}
};
}
private void buildlocationrequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(10);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case FINE_LOCATION_REQUEST_CODE :
if(grantResults.length>0)
{
if(grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Granted",Toast.LENGTH_LONG).show();
}
else if(grantResults[0]==PackageManager.PERMISSION_DENIED)
{
Toast.makeText(this,"Permission Denied You need to enable first",Toast.LENGTH_LONG).show();
}
}
}
}
}
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.my.gpstracker_myown"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation'com.google.android.gms:play-services-location:16.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Я тестирую на реальном устройстве, а не на эмуляторе, и не получаю никаких обновлений местоположения, но на верхнем значке местоположения появляется значок (это означает, что приложение запрашивает местоположение).
Заранее спасибо