java - 如何修复某些手机中每秒发送数据的位置?

标签 java android

这不是重复的,因为我的问题有点不同。

我尝试在应用程序关闭时每 20 分钟发送一次位置信息,但是当我使用时间间隔时,它不会很好地工作,所以我尝试使用 Handler 来获取数据每 20 分钟一类。另外,代码引用是基于另一个我不记得的问题的答案,我只是更改了一些部分。

此构建基于一些答案,这是我在做作业时尝试的,当我尝试使用 minTimeInterver 应用程序时以某种方式忽略位置更改,这就是我使用处理程序的原因。所以整个想法是每 20 分钟发送一次位置信息。

这是 Activity 设置:

    mYourService = new MyService();
    mServiceIntent = new Intent(this, mYourService.getClass());
    if (!isMyServiceRunning(mYourService.getClass())) {
        startService(mServiceIntent);
    }

服务:

public class MyService extends Service {

    private static final String TAG = "MyServiceTTT";
    public int counter = 0;
    private LocationManager mLocationManager = null;
    private static int LOCATION_INTERVAL = 900000;
    private static ApiClient mApi;
    private AppDatabase appDatabase;
    private static final float LOCATION_DISTANCE = 10f;
    private ArrayList<Map> maps;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location.getLongitude() + " - " + location.getLatitude());

            String status = AppPref.getInstance().getUserStatus();

            if (AppPref.getInstance().getShiftService()) {
                switch (status) {
                    case "true":
                        Log.e(TAG, "1");
                        TimeZone timeZone = TimeZone.getTimeZone("Asia/Tehran");
                        Calendar cal = Calendar.getInstance(timeZone);
                        cal.add(Calendar.DATE, 0);

                        SimpleDateFormat format1 = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);

                        String formatted = format1.format(cal.getTime());

                        String star = AppPref.getInstance().getUserStartAt();
                        String en = AppPref.getInstance().getUserEndAt();
                        try {

                            Log.e(TAG, "2");
                            if (TimeConditioner.isTimeBetweenTwoTime(star, en, formatted)) {
                                Log.e(TAG, "3");
                                OnlineCordinateRequest onlineCordinateRequest = new OnlineCordinateRequest();
                                onlineCordinateRequest.user_id = Integer.parseInt(AppPref.getInstance().getUserID());
                                onlineCordinateRequest.lat = location.getLatitude();
                                onlineCordinateRequest.lng = location.getLongitude();
                                onlineCordinateRequest.methodz = "online";
                                onlineCordinateRequest.status = "none";
                                getApi().cordinate(onlineCordinateRequest).enqueue(new Callback<GeneralCallBack>() {
                                    @Override
                                    public void onResponse(Call<GeneralCallBack> call, Response<GeneralCallBack> response) {
                                        Log.i(TAG, "Done");
                                    }

                                    @Override
                                    public void onFailure(Call<GeneralCallBack> call, Throwable t) {
                                        Log.i(TAG, "Failed");
                                        createMap(Integer.parseInt(AppPref.getInstance().getUserID()), location.getLatitude(), location.getLongitude());

                                    }
                                });
                            } else {
                                Log.i(TAG, "Failed");
                                Log.e(TAG, "4");
                            }
                        } catch (ParseException e) {
                            Log.i(TAG, "Failed");
                            Log.e(TAG, "5");
                        }

                        break;
                    case "false":
                        Log.i(TAG, "Que False");
                        Log.e(TAG, "6");
                        break;
                    default:
                        Log.i(TAG, "Que Default");
                        Log.e(TAG, "7");
                }
            } else {
                Log.e(TAG, "8");
                OnlineCordinateRequest onlineCordinateRequest = new OnlineCordinateRequest();
                onlineCordinateRequest.user_id = Integer.parseInt(AppPref.getInstance().getUserID());
                onlineCordinateRequest.lat = location.getLatitude();
                onlineCordinateRequest.lng = location.getLongitude();
                onlineCordinateRequest.methodz = "online";
                onlineCordinateRequest.status = "none";
                getApi().cordinate(onlineCordinateRequest).enqueue(new Callback<GeneralCallBack>() {
                    @Override
                    public void onResponse(Call<GeneralCallBack> call, Response<GeneralCallBack> response) {
                        Log.i(TAG, "Done");
                        Log.e(TAG, "9");
                    }

                    @Override
                    public void onFailure(Call<GeneralCallBack> call, Throwable t) {
                        Log.i(TAG, "Failed");
                        Log.e(TAG, "10");
                        createMap(Integer.parseInt(AppPref.getInstance().getUserID()), location.getLatitude(), location.getLongitude());

                    }
                });
            }
            Log.e(TAG, "11");
            mLastLocation.set(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    private void createMap(int user_id, double lat, double lng) {

        TimeZone timeZone = TimeZone.getTimeZone("Asia/Tehran");
        Calendar cal = Calendar.getInstance(timeZone);
        cal.add(Calendar.DATE, 0);

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd k:m:s", Locale.ENGLISH);
        String formatted = format1.format(cal.getTime());

        new MyService.CreateMapLogAsyncTask().execute(new Map(0, user_id, lat, lng, "offline", "opened", formatted));
    }

    private class CreateMapLogAsyncTask extends AsyncTask<Map, Void, Void> {

        @Override
        protected Void doInBackground(Map... maps) {

            long id = appDatabase.getMapDAO().addMap(maps[0]);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Log.i(TAG, "Added to DB");
        }
    }

    public ApiClient getApi() {
        if (mApi == null) {
            mApi = ApiService.getClient().create(ApiClient.class);
        }
        return mApi;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            Log.e("MyServiceTTT", "Testing Data111 : ");
        }
//            startMyOwnForeground();
        else {
            Log.e("MyServiceTTT", "Testing Data222 : ");
        }
//            startForeground(1, new Notification());
//        startTimer();
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void startMyOwnForeground() {

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "LOCATION_INTERVAL");
        super.onStartCommand(intent, flags, startId);
        appDatabase = AppDatabase.getInstance(getApplicationContext());
        startTimer();
        return START_STICKY;
    }

    MyService.LocationListener[] mLocationListeners = new MyService.LocationListener[]{
            new MyService.LocationListener(LocationManager.PASSIVE_PROVIDER)
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, Restarter.class);
        this.sendBroadcast(broadcastIntent);
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listener, ignore", ex);
                }
            }
        }
    }

    final Handler updateHandler = new Handler(Looper.getMainLooper());

    public void startTimer() {
        int timerTime = Integer.parseInt(AppPref.getInstance().getIntervalMiliSeconds()) * 60000;
        LOCATION_INTERVAL = timerTime;
        Log.i(TAG, String.valueOf(timerTime));
        Runnable runnable = new Runnable() {
            public void run() {

                initializeLocationManager();

                try {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.PASSIVE_PROVIDER,
                            LOCATION_INTERVAL,
                            LOCATION_DISTANCE,
                            mLocationListeners[0]
                    );

                } catch (java.lang.SecurityException ex) {
                    Log.i(TAG, "fail to request location update, ignore", ex);
                } catch (IllegalArgumentException ex) {
                    Log.d(TAG, "network provider does not exist, " + ex.getMessage());
                }
                updateHandler.postDelayed(this, timerTime); // determines the execution interval
            }
        };
        updateHandler.post(runnable);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

最佳答案

实现JobService是最好的选择,您可以根据自己的需求进行修改。更多信息请参见官方site

关于java - 如何修复某些手机中每秒发送数据的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279676/

相关文章:

android - 后退按钮事件在后台移动应用程序

android - AudioRecord 有时会跳过音频数据

java - Selenium Webdriver 断言 2 个元素在 Java 中包含相同的数字

java - 在 Java 中重命名驱动器标签

java - 理解 Stream.generate 静态方法签名的问题

android - 使用 ProGuard 导致 ACRA 出现 NoSuchFieldError

java - react native : Volume Button Should Only Control Media (Android)

android - 带有 ExpandableListView 的 BaseExpandableListAdapter 返回错误的 subview

java - Hibernate 为实体实例变量获取 null?

java - 使用 jquery ajax 调用 servlet 加载数据?