Android 从远程设备获取位置数据

Android 从远程设备获取位置数据,android,Android,有很多教程可以帮助你找到一个目标的位置 用户的设备,我想从司机的设备获取此信息,因为我正在构建一个应用程序 对于出租车公司来说,我们的想法是传递这些位置数据 到客户应用程序,以便客户可以跟踪驾驶员的 地点。 我该如何解决这个问题???你有两个选择,也许更多 op1: 创建后台服务并使用位置侦听器,在位置更改中调用api并更新驱动程序的最后位置,以及在后台服务中使用计时器调用客户应用程序api(例如:每30秒调用驱动程序的最后一个api) op2: 创建通知服务,每次您想要发送推送到驱动程序时,在

有很多教程可以帮助你找到一个目标的位置 用户的设备,我想从司机的设备获取此信息,因为我正在构建一个应用程序 对于出租车公司来说,我们的想法是传递这些位置数据 到客户应用程序,以便客户可以跟踪驾驶员的 地点。
我该如何解决这个问题???

你有两个选择,也许更多

op1: 创建后台服务并使用位置侦听器,在位置更改中调用api并更新驱动程序的最后位置,以及在后台服务中使用计时器调用客户应用程序api(例如:每30秒调用驱动程序的最后一个api)

op2: 创建通知服务,每次您想要发送推送到驱动程序时,在notif服务中,当收到这种类型的notif时,调用api并更新最后一个位置 在每次位置更新中,向客户发送推送

这是我的方式:(我使用音频和其他一些东西,删除任何你不喜欢的东西

public class LocationService extends Service {

private static final String TAG = "LocationService";
private DBHelper DBConnection;
private Context context;
public LocationManager locationManager;
public MyLocationListener listener;
public static boolean gpsEnable = true;
private NotificationManager notificationManager;
private int lastVolume;
private AudioManager audioManager;
private boolean sendingListInProgress = false;
public static MediaPlayer mediaPlayer;
//private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(); 

@Override
public void onCreate() {
    super.onCreate();
    context = this;
    DBConnection = new DBHelper(context);
    DBConnection.DBCreate(context);
    IntentFilter i = new IntentFilter();
    i.addAction("android.intent.action.update_map");
    //registerReceiver(broadcastReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    try {
        FirebaseCrash.log("Activity created");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new MyLocationListener();
        int minDistance = 10;
        int time = 8000;
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            return START_NOT_STICKY;
        else
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, minDistance, listener);

        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "N", NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);
            channel.setSound(null, null);
            channel.setDescription(String.valueOf(getText(R.string.app_name2)));
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
        builder.setAutoCancel(false);
        builder.setContentTitle(getText(R.string.app_name2));
        builder.setSmallIcon(R.drawable.ic_launcher_small);
        builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher));
        builder.setOngoing(true);
        builder.setContentIntent(PendingIntent.getActivity(context, 479, new Intent(context, SplashActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK), 0));

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            startForeground(13, builder.build());
        } else {
            notificationManager.notify(13, builder.build());
        }
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        lastVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    } catch (Exception ex) {
        //FirebaseCrash.logcat(Log.ERROR, TAG, "NPE caught");
        //FirebaseCrash.report(ex);
    }
    return START_STICKY;
}

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

@Override
public void onDestroy() {
    //unregisterReceiver(broadcastReceiver);
    if (Cache.getInt(Cache.status) == 1) {
        startService(new Intent(context, LocationService.class));
    } else {
        if (locationManager != null && listener != null)
            locationManager.removeUpdates(listener);
        listener = null;
        locationManager = null;
        if (notificationManager != null)
            notificationManager.cancel(13);
        super.onDestroy();
    }
}

private void playAlarmSound() { //play alarm when gps turn off
    if (mediaPlayer != null)
        mediaPlayer.stop();
    mediaPlayer = new MediaPlayer();
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
    try {
        AssetFileDescriptor afd = this.getAssets().openFd("analog_alarm.mp3");
        mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        mediaPlayer.prepare();
    } catch (Exception ignored) {
    }
    mediaPlayer.start();
    checkGPS();
}

private void checkSound() {
    if (gpsEnable || Cache.getInt(Cache.status) == 0) {
        if (mediaPlayer != null)
            mediaPlayer.stop();
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, lastVolume, 0);
    } else {
        new Handler().postDelayed(this::checkSound, 1500);
        playAlarmSound();
    }
}

public class MyLocationListener implements LocationListener {

    public void onLocationChanged(final Location locations) {
        if (locations.getLatitude() > 20 && locations.getLongitude() > 20) {
            App.lastLat = locations.getLatitude(); //save last location some where
            App.lastLng = locations.getLongitude();//save last location some where
            Cache.set(Cache.lat, locations.getLatitude());//save last location some where
            Cache.set(Cache.lng, locations.getLongitude());//save last location some where
        }
        SendLocation(locations, isNetworkEnable());//api call
    }

    public void onProviderDisabled(String provider) {
        gpsEnable = false;
        if (Cache.getInt(Cache.status) == 1) { // true means active
            DBConnection.saveReport(context, new OfficialDriverEvents(0));
            checkSound();
            checkGPS();
        }
    }

    public void onProviderEnabled(String provider) {
        gpsEnable = true;
        DBConnection.saveReport(context, new OfficialDriverEvents(1));
        checkSound();
        checkGPS();
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

private void reportChangeToServer(List<OfficialDriverEvents> list) {
    ApiService apiService = ApiClient.getClient().create(ApiService.class);
    Call<Integer> call = apiService.officialDriverEvents(list);
    call.enqueue(new Callback<Integer>() {
        @Override
        public void onResponse(@NonNull Call<Integer> call, @NonNull Response<Integer> response) {
            if (response.code() == 200)
                try {
                    if (response.body() != null && response.body() == 1) {
                        DBHelper.database.execSQL("DELETE FROM 'event'");
                    }

                } catch (Exception ignored) {
                }
        }

        @Override
        public void onFailure(@NonNull Call<Integer> call, @NonNull Throwable t) {
        }
    });
}

private void SendLocation(Location getLocation, boolean isNetworkEnable) {
    if (!gpsEnable) {
        checkGPS();
    }
    if (isNetworkEnable) {
        checkDatabaseReportList();
        if (!sendingListInProgress) {
            checkDatabaseLocationList();
        }
    }
    if (getLocation.getLatitude() > 20 && getLocation.getLongitude() > 20) {
        Locations location = new Locations();
        location.setStrIMEI(Cache.getString(Cache.imei));
        location.setStrUnitId(Cache.getString(Cache.id));
        location.setLat(getLocation.getLatitude());
        location.setLon(getLocation.getLongitude());
        location.setDistance(0);
        location.setLogDate(Time.getNowPersianDate());
        location.setLogTime(Time.getNowTime());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            location.setViSpeed(String.valueOf((int) (getLocation.getSpeedAccuracyMetersPerSecond() * 3.6)));
            location.setAccurecy(String.valueOf(getLocation.getVerticalAccuracyMeters()));
            location.setSteps(String.valueOf(getLocation.getBearingAccuracyDegrees()));
        } else {
            location.setViSpeed(String.valueOf((int) (getLocation.getSpeed() * 3.6)));
            location.setAccurecy(String.valueOf(getLocation.getAccuracy()));
            location.setSteps(String.valueOf(getLocation.getBearing()));
        }
        if (isNetworkEnable) {
            SendRequest(location);
        } else {
            DBConnection.saveData(context, location);//request failed save in db for send this later
        }
    }
}

private void checkDatabaseLocationList() {
    List<Locations> lstLocations = DBConnection.openData(context);
    if (lstLocations != null && lstLocations.size() > 0) {
        sendingListInProgress = true;
        SendRequestList(lstLocations);
    } else {
        sendingListInProgress = false;
    }
}

private void checkDatabaseReportList() { // send all failed requests
    List<OfficialDriverEvents> list = DBConnection.getReport(context);
    if (list != null && list.size() > 0)
        reportChangeToServer(list);
}

private void SendRequestList(List<Locations> lstLocations) {
    ApiService apiService = ApiClient.getClient().create(ApiService.class);

    Call<Integer> call = apiService.saveMobileMovementList(lstLocations);
    call.enqueue(new Callback<Integer>() {
        @Override
        public void onResponse(@NonNull Call<Integer> call, @NonNull Response<Integer> response) {
            if (response.code() == 200 && response.body() != null && response.body() == 1) {
                try {
                    DBHelper.database.execSQL("DELETE FROM 'gps' WHERE id IN (SELECT id FROM 'gps' LIMIT 1000)");
                    Log.d("peyloc", "list removed");
                } catch (Exception e) {
                    Log.d("peyloc", "list 200 catch: " + e.getMessage());
                } finally {
                    new Handler().postDelayed(() -> checkDatabaseLocationList(), 20000);
                    Log.d("peyloc", "finally check for offline list");
                }
            } else {
                new Handler().postDelayed(() -> checkDatabaseLocationList(), 20000);
                sendingListInProgress = false;
                Log.d("peyloc", "list not 200");
            }
        }

        @Override
        public void onFailure(@NonNull Call<Integer> call, @NonNull Throwable t) {
            sendingListInProgress = false;
            Log.d("peyloc", "list onFailure");
        }
    });
}

private void checkGPS() { //check gps
    if (!gpsEnable) {
        if (!TurnOnLocationActivity.isRun && !TripAcceptActivity.isRun && !HomeFragment.isRun && !com.rayanandisheh.peysepar.helper.Location.isShowing)
            context.startActivity(new Intent(context, TurnOnLocationActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//            checkSound();
    }
}

private boolean isNetworkEnable() { //check network
    NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

private void SendRequest(final Locations location) {
    ApiService apiService = ApiClient.getClient().create(ApiService.class);
    Call<Integer> call = apiService.saveMobileMovement(location);
    call.enqueue(new Callback<Integer>() {
        @Override
        public void onResponse(@NonNull Call<Integer> call, @NonNull Response<Integer> response) {
            if (response.code() == 200 && response.body() != null && response.body() == 1)
                Log.d("peyloc", "200 ok");
            else {
                Log.d("peyloc", "200 not ok");
                DBConnection.saveData(context, location);//request failed save in db for send this later
            }
        }

        @Override
        public void onFailure(@NonNull Call<Integer> call, @NonNull Throwable t) {
            Log.d("peyloc", "onFailure");
            DBConnection.saveData(context, location);//request failed save in db for send this later
        }
    });
}
}
公共类定位服务扩展服务{
私有静态最终字符串TAG=“LocationService”;
专用数据库连接;
私人语境;
公共场所经理;
公共MyLocationListener;
公共静态布尔gpsEnable=true;
私人通知经理通知经理;
私有卷;
私人音频经理;
私有布尔sendingListInProgress=false;
公共静态媒体播放器;
//private BroadcastReceiver BroadcastReceiver=新的BroadcastReceiver();
@凌驾
public void onCreate(){
super.onCreate();
上下文=这个;
DBConnection=newdbhelper(上下文);
DBConnection.DBCreate(上下文);
IntentFilter i=新IntentFilter();
i、 addAction(“android.intent.action.update_map”);
//registerReceiver(broadcastReceiver,new IntentFilter(LocationManager.PROVIDERS\u CHANGED\u ACTION));
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
super.onStartCommand(intent、flags、startId);
试一试{
FirebaseCrash.log(“创建的活动”);
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
listener=新的MyLocationListener();
智力距离=10;
整数时间=8000;
if(ActivityCompat.checkSelfPermission(context、Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ActivityCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予)
返回开始时间不粘;
其他的
locationManager.RequestLocationUpdate(locationManager.GPS_提供程序、时间、距离、侦听器);
notificationManager=(notificationManager)getSystemService(通知服务);
if(android.os.Build.VERSION.SDK\u INT>=android.os.Build.VERSION\u code.O){
NotificationChannel通道=新的NotificationChannel(通道ID,“N”,NotificationManager.IMPORTANCE\u默认值);
通道启用灯(真);
channel.setSound(空,空);
channel.setDescription(String.valueOf(getText(R.String.app_name2));
notificationManager.createNotificationChannel(频道);
}
NotificationCompat.Builder=新建NotificationCompat.Builder(上下文,通道ID);
builder.setAutoCancel(false);
setContentTitle(getText(R.string.app_name2));
builder.setSmallIcon(R.drawable.ic_launcher_small);
setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_启动器));
builder.setcongressing(true);
builder.setContentIntent(PendingIntent.getActivity)(上下文,479,新意图(上下文,SplashActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK),0);
if(android.os.Build.VERSION.SDK\u INT>=android.os.Build.VERSION\u code.O){
startForeground(13,builder.build());
}否则{
notificationManager.notify(13,builder.build());
}
audioManager=(audioManager)getSystemService(音频服务);
lastVolume=audioManager.getStreamVolume(audioManager.STREAM_MUSIC);
}捕获(例外情况除外){
//firebasecash.logcat(Log.ERROR,标记为“NPE已捕获”);
//FirebaseCrash.报告(ex);
}
返回开始时间;
}
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
公共空间{
//未注册接收器(广播接收器);
if(Cache.getInt(Cache.status)==1){
startService(新意图(context,LocationService.class));
}否则{
if(locationManager!=null&&listener!=null)
locationManager.RemoveUpdate(侦听器);
listener=null;
locationManager=null;
如果(notificationManager!=null)
通知经理。取消(13);
super.ondestory();
}
}
private void playAlarmSound(){//在gps关闭时播放警报
如果(mediaPlayer!=null)
mediaPlayer.stop();
mediaPlayer=新的mediaPlayer();
audioManager.setStreamVolume(audioManager.STREAM_MUSIC,audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC),0);
试一试{
AssetFileDescriptor afd=this.getAssets().openFd(“模拟报警.mp3”);
setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mediaPlayer.prepare();
}捕获(忽略异常){
}
mediaPlayer.start();
检查GPS();
}
私人空位检查声音(){
if(gpsEnable | | Cache.getInt(Cache.status)==0){
如果(mediaPlayer!=null)
mediaPlayer.stop();
audioManager.setStreamVolume(audioManager.STREAM_音乐,最后一卷,0);
}否则{
new Handler().postDelayed(this::checkSound,1500);
播放报警声音();
}
}
公共类MyLocationListener实现LocationListener{
更改了公共无效位置(最终位置){
if(locations.getLatitude()>20&&loc