Widget gps (android studio)

Всем доброго дня. Хотел сделать виджет в котором считывались бы текущие координаты GPS. Но что-то пошло не так. Сделал настройку, что бы виджет сам обновлялся очень часто. Но координаты GPS получаю только один, два раза и все затихает. Не могу понять почему так происходит?

package com.example.wiget004;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;

import java.text.SimpleDateFormat;
import java.util.Calendar;


public class Widget004Test extends AppWidgetProvider {
    final String UPDATE_ALL_WIDGETS = "update_all_widgets";
    private LocationManager locationManager;

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        Log.d("myLogs", "updateAppWidget");
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        Log.d("myLogs", "onUpdate");
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // When the user deletes the widget, delete the preference associated with it.
        Log.d("myLogs", "onDeleted");
        for (int appWidgetId : appWidgetIds) {
            Widget004TestConfigureActivity.deleteTitlePref(context, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        Log.d("myLogs", "onEnabled");
        Intent intent = new Intent(context, Widget004Test.class);
        intent.setAction(UPDATE_ALL_WIDGETS);
        PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
                6000, pIntent);
    }

    @Override
    public void onDisabled(Context context) {
        Log.d("myLogs", "onDisabled");
        Intent intent = new Intent(context, Widget004Test.class);
        intent.setAction(UPDATE_ALL_WIDGETS);
        PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(pIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.d("myLogs", "onReceive");

        if (intent.getAction().equalsIgnoreCase(UPDATE_ALL_WIDGETS)) {
            ComponentName thisAppWidget = new ComponentName(
                    context.getPackageName(), getClass().getName());
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(context);
            int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
            for (int appWidgetID : ids) {
                updateAppWidget(context, appWidgetManager, appWidgetID);
            }
        }


        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);        // Getting GPS status
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 10,locationListener);


    }



    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            showLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d("myLogs","function onProviderDisabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.d("myLogs","!!!onProviderEnabled");
            showLocation(locationManager.getLastKnownLocation(provider));
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("myLogs","!!!onStatusChanged");
            if (provider.equals(LocationManager.GPS_PROVIDER)) {
                Log.d("myLogs","Status GPS_PROVIDER: " + String.valueOf(status));
            } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
                Log.d("myLogs","Status NETWORK_PROVIDER: " + String.valueOf(status));
            }
        }


        private void showLocation(Location location) {
            Log.d("myLogs","showLocation");
            if (location == null)
                return;
            if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                Log.d("myLogs",  "GPS_PROVIDER Широта="+String.format("%1$.4f" ,location.getLatitude())+"   Долгота="+String.format("%1$.4f",location.getLongitude()) );
            } else if (location.getProvider().equals(
                    LocationManager.NETWORK_PROVIDER)) {
                Log.d("myLogs", " NETWORK_PROVIDER Широта="+String.format("%1$.4f" ,location.getLatitude())+"   Долгота="+String.format("%1$.4f",location.getLongitude()) );
            }
        }


    };


}

Ответы (1 шт):

Автор решения: андрей

если gps проверяю через обычный activity то все работает, координаты постоянно считывает, а в виджете тупик

package com.example.testgps;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView tvEnabledGPS;
    TextView tvStatusGPS;
    TextView tvLocationGPS;
    TextView tvEnabledNet;
    TextView tvStatusNet;
    TextView tvLocationNet;

    private LocationManager locationManager;
    StringBuilder sbGPS = new StringBuilder();
    StringBuilder sbNet = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("myLogs","onCreate");
        setContentView(R.layout.activity_main);
        tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
        tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
        tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
        tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
        tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
        tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    }



    @Override
    protected void onResume() {
        super.onResume();
        Log.d("myLogs","onResume");
        int MY_PERMISSIONS = 1;
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
               && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS);
        }

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300 * 10, 10, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 300 * 10, 10,locationListener);

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("myLogs","onPause");
        locationManager.removeUpdates(locationListener);
    }






    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            Log.d("myLogs","onLocationChanged");
            if (location != null)
            {
                Log.d("myLogs", "Широта="+String.format("%1$.4f",location.getLatitude()));
                Log.d("myLogs", "Долгота="+location.getLongitude());

            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d("myLogs","onProviderDisabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.d("myLogs","onProviderEnabled");
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("myLogs","onStatusChanged");

        }
    };




}
→ Ссылка