M
M
m0t0d0r2022-02-03 09:57:03
Java
m0t0d0r, 2022-02-03 09:57:03

GPS geolocation in the stream?

The task is to determine the coordinates in a separate thread, and then return the coordinates to the global variable through synchronization. Without a thread, the code worked fine, but it doesn't want to in a thread. A request for access to geolocation data arrives, I click to allow access, and then the application is cut down, while there are no errors in Android Studio, everything compiles successfully. I'm into android java programming, layman, I need help.

package com.example.getlocation;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Поток определения локации
        Thread MyThread = new Thread(MyGetLocationThread);
        MyThread.start();
    }

    // Поток определения локации
    Runnable MyGetLocationThread = new Runnable() {
        public void run() {
            LocationListener myLocationListener;
            LocationManager myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            int PERMISSION_REQUEST = 1;

            myLocationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double Longitude = location.getLongitude(); // Долгота
                    double Latitude = location.getLatitude(); // Широта
                    System.out.println(Double.toString(Latitude)+"  --  "+Double.toString(Longitude));
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void onProviderEnabled(String s) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void onProviderDisabled(String s) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }
            };

            // Запрос разрешения у пользователя на доступ к локации
            // this был заменен на MainActivity.this
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)==-1){
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
            }
            myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, myLocationListener);
        }
    };

}


Please note that I am new to Java programming, I hope for an exact answer, what and where to rewrite, correct. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmtm, 2022-02-03
@Dmtm

more or less like this

override void onResume(..)  { //повторные запуски после того как пермишен выдан
// Запрос разрешения у пользователя на доступ к локации
            // this был заменен на MainActivity.this
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)==-1){
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
            } else {
                   if (thread == null ) {
                          thred = new Thread
                    }
            }
}
override fun onRequestPermissionsResult (...) {
//если пермишен только что выдан то
  if (thread == null ) {
                          thred = new Thread
                    }

by if (thread == null ) we protect ourselves from restarting

M
m0t0d0r, 2022-02-03
@m0t0d0r

Found a problem

package com.example.getlocation;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;

public class MainActivity extends AppCompatActivity {
    int PERMISSION_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Получаем права на доступ к локацие
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)==-1){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
            System.out.println("  --  УПС");
        }
        // Как дождаться принятия решения пользователем?

        //Поток определения локации
        Thread MyThread = new Thread(MyGetLocationThread);
        MyThread.start();
    }

    // Поток определения локации
    Runnable MyGetLocationThread = new Runnable() {
        public void run() {
            Looper.prepare();
            LocationListener myLocationListener;
            LocationManager myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            myLocationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double Longitude = location.getLongitude(); // Долгота
                    double Latitude = location.getLatitude(); // Широта
                    System.out.println(Latitude+"  --  "+Longitude);
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void onProviderEnabled(String s) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void onProviderDisabled(String s) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }
            };

            // Запрос разрешения у пользователя на доступ к локации
            // this был заменен на MainActivity.this
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)==0){
                myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, myLocationListener);
            }
            Looper.loop();
        }
    };

}

I should have hung a looper.
There is another question.
// Получаем права на доступ к локацие
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)==-1){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST);
            System.out.println("  --  УПС");
        }
        // Как дождаться принятия решения пользователем?

Oops is not linear, that is, I have not yet made a decision on the requestPermissions request, and the application is already moving on. Does not wait for a response from the user. Maybe someone knows how to suspend the program until a decision is made. Thank you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question