如何在应用重新启动并且用户已授予位置访问权限时再次启动服务 [英] How to start service again when App Restarts and User already Granted Location access

查看:190
本文介绍了如何在应用重新启动并且用户已授予位置访问权限时再次启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用在后台运行的服务来实现一个简单的gpsTracker,如下所示:

  public class MyService extends Service 
{
private static final String TAG =BOOMBOOMTESTGPS;
私人LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;

private final IBinder mBinder = new LocalBinder();
私人意图意图;
上下文上下文;

位置mLastLocation;

public class LocalBinder extends Binder {
public MyService getServerInstance(){
return MyService.this;
}
}

public Location getLocation(){
return mLastLocation;



private class LocationListener实现了android.location.LocationListener
{

public LocationListener(String provider)
{
Log.e(TAG,LocationListener+ provider);
mLastLocation =新位置(供应商);
}

@Override
public void onLocationChanged(Location location)
{
Log.e(TAG,onLocationChanged:+ location);
mLastLocation.set(location);
Log.d(HELLO,String.valueOf(mLastLocation.getLatitude()));


$ b @Override
public void onProviderDisabled(String provider)
{
Log.e(TAG,onProviderDisabled:+供应商);
}

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

$ b @Override
public void onStatusChanged(String provider,int status,Bundle extras)
{
Log.e(TAG,onStatusChanged: +提供者);



LocationListener [] mLocationListeners = new LocationListener [] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER )
};


@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
Log.e(TAG,onStartCommand) ;
context = getApplicationContext();
super.onStartCommand(intent,flags,startId);
返回START_STICKY;
}


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



$ b @Override
public void onCreate()
{
Log.e(TAG,onCreate );
initializeLocationManager();
尝试{
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,
mLocationListeners [1]);
} catch(java.lang.SecurityException ex){
Log.i(TAG,无法请求位置更新,忽略,前);
} catch(IllegalArgumentException ex){
Log.d(TAG,网络提供者不存在,+ ex.getMessage());
}
尝试{
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,
mLocationListeners [0]);
} catch(java.lang.SecurityException ex){
Log.i(TAG,无法请求位置更新,忽略,前);
} catch(IllegalArgumentException ex){
Log.d(TAG,gps provider does not exist+ ex.getMessage());
}
}

@Override
public void onDestroy()
{
Log.e(TAG,onDestroy);
super.onDestroy();如果(mLocationManager!= null){
for(int i = 0; i< mLocationListeners.length; i ++){
try {
mLocationManager.removeUpdates(mLocationListeners [i ]);
} catch(Exception ex){
Log.i(TAG,无法移除位置列表,忽略,ex);




$ b private void initializeLocationManager(){
Log.e(TAG,initializeLocationManager);
mLocationManager =(LocationManager)getSystemService(LOCATION_SERVICE);
if(mLocationManager == null){
mLocationManager =(LocationManager)getApplicationContext()。getSystemService(Context.LOCATION_SERVICE);
}
}

并且在这之后ii开始主要活动的服务像这样:

  public class MainActivity extends AppCompatActivity {

private BroadcastReceiver receiver;
IntentFilter过滤器;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void initService(View view){
checkPermissions();
startService(new Intent(this,MyService.class)); (),$ {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager .PERMISSION_GRANTED&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED ){

ActivityCompat.requestPermissions(this,new String [] {android.Manifest.permission.ACCESS_COARSE_LOCATION},
30);



$ b public void nextAct(View view){
Intent i = new Intent(this,GpsGetCoordinates.class);
startActivity(i);
}
}

我已经获得了我想要的位置,但是如何我可以在重新启动应用程序时获取位置吗?它只是当我提供一个位置,如果用户启动的应用程序,并没有移动它失败任何提示呢?

解决方案

你必须在两种情况下启动该服务: -
$ b <1>当用户授予位置访问权限时。



所以你必须同时处理两种方式

  public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
$ b $ public boolean checkLocationPermission(){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission。ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){

//我们应该显示一个解释吗?
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){

//异步显示给用户的解释* - 不要阻止
//此线程正在等待用户的响应!在用户
//看到解释后,再次尝试请求权限。
新的AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok,新的DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface,int i){
//一旦显示解释后提示用户
ActivityCompat.requestPermissions( MainActivity.this,
new String [] {Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
。显示();


}其他{
//无需解释,我们可以申请许可。
ActivityCompat.requestPermissions(this,
new String [] {Manifest.permission。ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
返回false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions [],int [] grantResults){
switch(requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION:{
//如果请求被取消,结果数组是空的。
if(grantResults.length> 0
&&& amp; grantResults [0] == PackageManager.PERMISSION_GRANTED){

//授予权限,是的!做你需要做的
//位置相关的任务。
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){


//开始您的服务这里
startService(new Intent(this,MyService.class));
}

} else {

// permission denied,boo!禁用依赖此权限的
//功能。

}
return;
}

}
}

OnResume()执行此操作

  @Override 
protected void onResume(){
super.onResume();

if(checkLocationPermission()){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission。ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
//在这里启动你的服务
startService(new Intent(this,MyService.class));




code


$ b

无需在中调用此方法onCreate()

  public void initService(View view){
//不需要在这里初始化权限和服务类
}


I am able to implement a simple gpsTracker using a service that runs on background like this:

public class MyService extends Service
{
    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private final IBinder mBinder = new LocalBinder();
    private Intent intent;
    Context context;

    Location mLastLocation;

    public class LocalBinder extends Binder {
        public MyService getServerInstance() {
            return MyService.this;
        }
    }

    public Location getLocation(){
        return mLastLocation;
    }


    private class LocationListener implements android.location.LocationListener
    {

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

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
            Log.d("HELLO",String.valueOf(mLastLocation.getLatitude()));
        }


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

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };


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


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



    @Override
    public void onCreate()
    {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } 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());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_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, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

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

and after this i i start the service on a main activity like this:

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver receiver;
    IntentFilter filter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void initService(View view){
        checkPermissions();
        startService(new Intent(this, MyService.class)); // inicia um serviço de obtenção de coordenadas GPS
    }

    private void checkPermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        30);
            }
        }
    }

    public void nextAct(View view){
        Intent i = new Intent(this,GpsGetCoordinates.class);
        startActivity(i);
    }
}

i already get the location when i desire, but how can i get the location when i restart the application? it just works when i provide a location if the user starts the app and doesn't move it faill any tip on this?

解决方案

Well You have to start the service in two cases:-

1) When user grant the location access.

2)When user already granted the permission after launching application again.

So you have to handle both the ways

Try this.

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission. ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission. ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(this)
                    .setTitle(R.string.title_location_permission)
                    .setMessage(R.string.text_location_permission)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION);
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission. ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {


                    //start your service here
                   startService(new Intent(this, MyService.class)); 
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

    }
}

The in OnResume() do this

@Override
protected void onResume() {
    super.onResume();

    if (checkLocationPermission()) {
       if (ContextCompat.checkSelfPermission(this,
           Manifest.permission. ACCESS_FINE_LOCATION)
           == PackageManager.PERMISSION_GRANTED) {
                  //start your service here
                       startService(new Intent(this, MyService.class)); 

       }
    }

}

No need to Call this Method in onCreate()

public void initService(View view){
       // no need to initialize permission and service class here
    }

这篇关于如何在应用重新启动并且用户已授予位置访问权限时再次启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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