Android检查用户是否关闭位置 [英] android check if user turned off location

查看:65
本文介绍了Android检查用户是否关闭位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,在该应用程序中,我必须不断保存用户的位置,然后将其发送到服务器.为此,我在服务中使用FusedLocationApis.这是我第一次要求用户打开位置信息. 运行良好.

I am building an application in which I have to constantly save user's location and then send it to the server. For that, I am using FusedLocationApis in a service. For the first time, I am asking user to turn on locations. It is working perfectly.

现在,如果用户无意中关闭了位置,该怎么办.我该如何通知他?开发人员是否必须照顾这一点,或者只是将其留给用户?

Now, what if the user unintentionally turns off the location. How should I inform him? Do developers have to take care of this or they just leave it to the user?

我想为此给他一个机器人通知.为此,我需要不断检查服务中启用的位置.我有一个适用的代码(功能checkHighAccuracyLocationMode).但是我应该在哪里进行检查(checkHighAccuracyLocationMode)? 每次在此服务中启用哪个功能?还是如果我能获得一个在用户关闭其位置时启动的功能?

I thought of giving him an android notification for this. For that, I need to constantly check our locations enabled in the service. I have a working code for that (function checkHighAccuracyLocationMode). But where should I do this check (checkHighAccuracyLocationMode) ? Which function is fired up every time in this service? Or If anyhow I can get a function that fires up when the user turned off his locations?

这是我的服务:

public class locationUpdatesService extends Service implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private Location mLastLocation;
private Location mCurrentLocation;
private String mLastUpdateTime;
private dataBaseHandler db_helper;

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

@Override
public void onCreate() {
    super.onCreate();
    db_helper = new dataBaseHandler(getApplicationContext(),dataBaseHandler.DATABASE_NAME,null,1);
}

@Override
public void onDestroy() {
    stopLocationUpdates();
    singletGoogleClientApi.setinstancenull();
    singletLocationRequest.setinstancenull();
    super.onDestroy();
}

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

private void initialise(){
    Log.e("ghgdhu","qaws");
    if (singletGoogleClientApi.getinstance().getGoogleApiCLient() == null) {
        singletGoogleClientApi.getinstance().setmSingletGoogleApiClient(new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build());
        singletGoogleClientApi.getinstance().getGoogleApiCLient().connect();
        createLocationRequest();
    }

    if(!singletGoogleClientApi.getinstance().getGoogleApiCLient().isConnected()){
        singletGoogleClientApi.getinstance().getGoogleApiCLient().connect();
        createLocationRequest();
    }
}

protected void createLocationRequest() {
    if(singletLocationRequest.getinstance().getLocationRequest() == null) {
        singletLocationRequest.getinstance().setSingletLocationRequest(new LocationRequest()
        .setInterval(10000)
        .setFastestInterval(5000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));
    }
}

public static boolean checkHighAccuracyLocationMode(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        //Equal or higher than API 19/KitKat
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            if (locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY){
                return true;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
    }else{
        //Lower than API 19
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (locationProviders.contains(LocationManager.GPS_PROVIDER) && locationProviders.contains(LocationManager.NETWORK_PROVIDER)){
            return true;
        }
    }
    return false;
}


@Override
public void onLocationChanged(Location location) {
    Log.e("qazxsw","inONLocationCHanged");
    mCurrentLocation = location;
    Log.e("loc : ",Double.toString(mCurrentLocation.getLatitude()));
    Toast.makeText(this, "My Location: "+Double.toString(mCurrentLocation.getLatitude())+ " , " + Double.toString(mCurrentLocation.getLongitude()),
            Toast.LENGTH_SHORT).show();
    mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
    if(!checkHighAccuracyLocationMode(getBaseContext())){
        Log.e("turned OFF","LOCATION");
    }
    else {
        Log.e("ONNNNN","LOCATION");
    }
    db_helper.Insert(mLastUpdateTime,mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(singletGoogleClientApi.
            getinstance().getGoogleApiCLient(), this);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

protected void startLocationUpdates() {
    try {
        if(singletLocationRequest.getinstance().getLocationRequest()!=null &&
                singletGoogleClientApi.getinstance().getGoogleApiCLient()!=null){
            Log.e("requesting","yES BRO");
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    singletGoogleClientApi.getinstance().getGoogleApiCLient(), singletLocationRequest.getinstance().getLocationRequest(), this);
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    singletGoogleClientApi.getinstance().getGoogleApiCLient());
        }
        else {
            initialise();
        }
    }
    catch (SecurityException e) {
        e.getStackTrace();
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.e("ON CONNECTION SUSPENDED","PETROL");

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e("COnnection ","DIESEL");

}

}

推荐答案

您可以使用位置状态更改后的receiver来了解用户何时手动旋转位置 GpsReceiver.java

You can use location state changed receiver to know when user manually turns of location GpsReceiver.java

public class GpsReceiver extends BroadcastReceiver {
    private final LocationCallBack locationCallBack;

    /**
     * initializes receiver with callback
     * @param iLocationCallBack Location callback
     */
    public GpsReceiver(LocationCallBack iLocationCallBack){
            this.locationCallBack = iLocationCallBack;
    }

    /**
     * triggers on receiving external broadcast
     * @param context Context
     * @param intent Intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            locationCallBack.onLocationTriggered();
        }
    }
}

创建一个interface以便将GPS更改传达给Activity

Create an interface to communicate GPS changes to Activity

public interface LocationCallBack {
    /**
     * on Location switch triggered
     */
    void onLocationTriggered();
}

ActivityonCreate()中注册receiver以开始收听GPS状态更改

Register receiver in onCreate() of Activity to start listening to GPS state changes

public void onCreate(Bundle savedInstance){
//---
registerReceiver(new GpsReceiver(new LocationCallBack() {
            @Override
            public void onLocationTriggered() {
                //Location state changed
            }
        }), new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
//---
}

这篇关于Android检查用户是否关闭位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆