виджет + gps

Ответить
tavka
Сообщения: 4
Зарегистрирован: 10 фев 2022, 12:32

виджет + gps

Сообщение tavka » 16 май 2022, 11:01

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

Код: Выделить всё

package com.example.wiget004;

public class Widget004Test extends AppWidgetProvider {

    final String UPDATE_ALL_WIDGETS = "update_all_widgets";
    private static String text01 = "---";
    private LocationManager locationManager;

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        Log.d("myLogs", "updateAppWidget");
        RemoteViews widgetView = new RemoteViews(context.getPackageName(),
                R.layout.widget004_test);
        widgetView.setTextViewText(R.id.appwidget_text, text01);
        appWidgetManager.updateAppWidget(appWidgetId, widgetView);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.d("myLogs", "onUpdate");
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        Log.d("myLogs", "onDeleted");
        for (int appWidgetId : appWidgetIds) {
            Widget004TestConfigureActivity.deleteTitlePref(context, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {

        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);        
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 5, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 6000, 5, locationListener);
        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 (locationManager != null) {
            Log.d("myLogs", "locationManager != null");
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                Log.d("myLogs", "location != null gps");
                text01= "Широта="+String.format("%1$.4f" ,location.getLatitude())+" Долгота="+String.format("%1$.4f",location.getLongitude());
                Log.d("myLogs", "getLastKnownLocation="+text01);
            }
            Location location2 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location2 != null) {
                Log.d("myLogs", "location != null net");
                text01= "Широта="+String.format("%1$.4f" ,location2.getLatitude())+" Долгота="+String.format("%1$.4f",location.getLongitude());
                Log.d("myLogs", "getLastKnownLocation="+text01);
            }
        }

        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);
            }
        }



    }


    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            Log.d("myLogs", "onLocationChanged");
            showLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d("myLogs", "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)) {
                text01= "Широта="+String.format("%1$.4f" ,location.getLatitude())+" Долгота="+String.format("%1$.4f",location.getLongitude());
                Log.d("myLogs", text01);
            } else if (location.getProvider().equals(
                    LocationManager.NETWORK_PROVIDER)) {
                text01= "Широта="+String.format("%1$.4f" ,location.getLatitude())+" Долгота="+String.format("%1$.4f",location.getLongitude());
                Log.d("myLogs", text01);
            }

        }


    };


}

tavka
Сообщения: 4
Зарегистрирован: 10 фев 2022, 12:32

Re: виджет + gps

Сообщение tavka » 18 май 2022, 09:18

если 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");

        }
    };




}


tavka
Сообщения: 4
Зарегистрирован: 10 фев 2022, 12:32

Re: виджет + gps

Сообщение tavka » 31 май 2022, 10:48

переписал через сервис, но данные по gps пару раз выводятся в лог, а топом какой-то игнор, то есть данные не выводятся по координатам, остальное все работает

Код: Выделить всё

package com.example.widget005;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import java.util.concurrent.TimeUnit;

public class MyService extends Service {
    final String LOG_TAG = "myLogs";
    LocationManager locationManager;
    private static final String ANDROID_CHANNEL_ID = "com.example.widget005.MyService";

    public MyService() {
        Log.d(LOG_TAG, "[service] MyService");
    }
    public void onCreate() {
        super.onCreate();
        Log.d(LOG_TAG, "[service] onCreate");
        Log.d(LOG_TAG, "[service] onCreate Build.VERSION.SDK_IN="+Build.VERSION.SDK_INT);
        Log.d(LOG_TAG, "[service] onCreate Build.VERSION_CODES.O="+Build.VERSION_CODES.O);

        locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("my_channel_01","my_service", NotificationManager.IMPORTANCE_DEFAULT);
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(1, notification);
        }else {
            Log.d(LOG_TAG, "[service] onCreate else");
            startForeground(1, new Notification());
        }

    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "[service] onStartCommand");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 10, locationListener);
        someTask();
        return START_STICKY;
    }
    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "[service] onDestroy");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        } else {
            stopSelf();
        }
    }



    void someTask() {
        Log.d(LOG_TAG, "[service] someTask");
        Log.d(LOG_TAG, "[service] тут долно быть считывание координат!!!!!!!!!!!!!!!!!!!!");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 10, locationListener);
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "[service] onBind");
        throw new UnsupportedOperationException("Not yet implemented");
    }


    private LocationListener locationListener;

    {
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("myLogs", "[service LocationListener] onLocationChanged");
                showLocation(location);

            }

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

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

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

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

        };
    }


}


Ответить