首页 > 解决方案 > 当应用程序被破坏或进入后台时,Android 位置服务停止工作

问题描述

我正在构建一个基于位置的应用程序,并且我创建了一个在后台运行的服务。当应用程序进入后台或被破坏并进入我的服务类时,如果我循环播放音频,它会完美运行。

即使我销毁应用程序并获取用户位置,音频仍在继续播放,我正在使用FusedLocationProviderClient API,它也适用于服务,但仅当应用程序用户转到其他应用程序或销毁应用程序时应用程序处于前台时,它没有获取位置但媒体播放器是在相同的服务中工作正常。

我的服务等级

public class ServiceClass extends Service {

    private MediaPlayer mediaplayer;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private LocationRequest locationRequest;
    private Context mContext;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        mContext = this;
        mediaplayer = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
        mediaplayer.setLooping(true);
        mediaplayer.start();
        getLocation();

        return START_STICKY;
    }

    public void getLocation() {

        Toast.makeText(mContext, "Engine X started YO", Toast.LENGTH_SHORT).show();

        fusedLocationProviderClient = new FusedLocationProviderClient(this);
        locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setFastestInterval(1000);
        locationRequest.setInterval(1000);

        fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback(){

            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                 Log.d("X_loc_BAck", ""+locationResult.getLastLocation().getAccuracy());
                Toast.makeText(mContext, ""+locationResult.getLastLocation().getLatitude(), Toast.LENGTH_SHORT).show();



            }
        },getMainLooper());

    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaplayer.stop();
        //Toast.makeText(this, "Service Desttroyed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        mediaplayer.stop();
        Intent i = new Intent(this, ServiceStopped.class);
        sendBroadcast(i);
        //Toast.makeText(this, "Service Task Removed", Toast.LENGTH_SHORT).show();
    }

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

标签: javaandroid

解决方案


根据文档

This method is suited for the foreground use cases. For background use cases, the PendingIntent version of the method is recommended, see requestLocationUpdates(LocationRequest, PendingIntent).

看看这个示例PendingIntent项目。


推荐阅读