Android RequestLocationUpdate的时间间隔是否未在前台服务中获取位置更新?

Android RequestLocationUpdate的时间间隔是否未在前台服务中获取位置更新?,android,service,location,locationlistener,foreground-service,Android,Service,Location,Locationlistener,Foreground Service,我创建了一个前台服务,每1分钟提取一次位置,但不知怎么的,这个服务在一分钟后不会提取位置 我在oreo后台之前创建了一个服务,在oreo前台服务之后创建了一个服务,我正在尝试注册位置更新,但问题是在关闭应用程序最多一分钟后,我得到了位置更新,之后除了前台服务通知外,我什么也得不到 MainActivity.java package com.practice.satya.foreground; import android.content.Intent; import android.os.Bu

我创建了一个前台服务,每1分钟提取一次位置,但不知怎么的,这个服务在一分钟后不会提取位置

我在oreo后台之前创建了一个服务,在oreo前台服务之后创建了一个服务,我正在尝试注册位置更新,但问题是在关闭应用程序最多一分钟后,我得到了位置更新,之后除了前台服务通知外,我什么也得不到

MainActivity.java

package com.practice.satya.foreground;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService();
    }
    public void startService() {
        if(Build.VERSION.SDK_INT >25){
            startForegroundService(new Intent(this, LocationFetchInForeground.class));
        }else{
            startService(new Intent(this, LocationFetchInForeground.class));
        }
    }
}



LocationUpdatesReceiver.java

package com.practice.satya.foreground;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;

public class LocationUpdatesReceiver extends BroadcastReceiver {
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        showNotification(context,"Location Changed","Updated location",intent);
    }
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void showNotification(Context context, String title, String body, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int notificationId = 93;
        String channelId = "testing";
        String channelName = "testing chanel";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(body);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
    }
}

LocationFetchInForeground.java

package com.practice.satya.foreground;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.hardware.TriggerEvent;
import android.hardware.TriggerEventListener;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class LocationFetchInForeground extends Service {
    private SensorManager sensorManager;
    private Sensor sensor;
    private TriggerEventListener triggerEventListener;

    /** indicates how to behave if the service is killed */
    int mStartMode;

    /** interface for clients that bind */
    IBinder mBinder;

    /** indicates whether onRebind should be used */
    boolean mAllowRebind;

    private static final String TAG = "MyLocationService";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 0f;

    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);
            Toast.makeText(getApplicationContext(),"onLocationUpdated", Toast.LENGTH_LONG).show();
            Intent intent=new Intent();
            showNotification(getApplicationContext(),"Location Changed","Updated location",intent);
            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);
        }
    }

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

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



    /** Called when the service is being created. */
    @Override
    public void onCreate() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //For creating the Foreground Service
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? getNotificationChannel(notificationManager) : "";
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
            Notification notification = notificationBuilder.setOngoing(true)
                    .setContentTitle("Location service")
                    .setContentText("This service is used to fetch location in background")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    // .setPriority(PRIORITY_MIN)
                    .setCategory(NotificationCompat.CATEGORY_SERVICE)
                    .build();
            startForeground(1, notification);
        }
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);

        triggerEventListener = new TriggerEventListener() {
            @Override
            public void onTrigger(TriggerEvent event) {
                // Do work
                Toast.makeText(getApplicationContext(), "Location Updated", Toast.LENGTH_LONG).show();
                Intent intent = new Intent();
                showNotification(getApplicationContext(), "Motion Changed", "Updated location", intent);
            }
        };
        if (sensor != null) {
            sensorManager.requestTriggerSensor(triggerEventListener, sensor);
        }


        Log.e(TAG, "onCreate");

        initializeLocationManager();
    }

    /** The service is starting, due to a call to startService() */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
            try {

//                Intent intenter = new Intent(this,LocationUpdatesReceiver.class);
//                PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intenter, PendingIntent.FLAG_UPDATE_CURRENT);
//                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
//                        LOCATION_INTERVAL,
//                        LOCATION_DISTANCE,
//                        proximityIntent);
                Intent intenter2 = new Intent(this,LocationUpdatesReceiver.class);
                PendingIntent proximityIntent2 = PendingIntent.getBroadcast(this, 0, intenter2, PendingIntent.FLAG_UPDATE_CURRENT);
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        LOCATION_INTERVAL,
                        LOCATION_DISTANCE,
                        proximityIntent2);
//
//            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, "network provider does not exist, " + ex.getMessage());
            }
        return START_STICKY;
    }

    /** A client is binding to the service with bindService() */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** Called when all clients have unbound with unbindService() */
    @Override
    public boolean onUnbind(Intent intent) {
        return mAllowRebind;
    }

    /** Called when a client is binding to the service with bindService()*/
    @Override
    public void onRebind(Intent intent) {

    }

    /** Called when The service is no longer used and is being destroyed */

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        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);
                }
            }
        }
    }
    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 String getNotificationChannel(NotificationManager notificationManager){
        String channelId = "ForegroundLocationFetch";
        String channelName = getResources().getString(R.string.app_name);
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }

    public void showNotification(Context context, String title, String body, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int notificationId = 234;
        String channelId = "testing";
        String channelName = "testing chanel";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(body);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
    }
}


package com.practice.satya.前台;
导入android.app.Notification;
导入android.app.NotificationChannel;
导入android.app.NotificationManager;
导入android.app.pendingent;
导入android.app.Service;
导入android.app.TaskStackBuilder;
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.hardware.Sensor;
导入android.hardware.SensorManager;
导入android.hardware.TriggerEvent;
导入android.hardware.TriggerEventListener;
导入android.location.location;
导入android.location.LocationManager;
导入android.os.Build;
导入android.os.Bundle;
导入android.os.IBinder;
导入android.support.annotation.RequiresApi;
导入android.support.v4.app.ActivityCompat;
导入android.support.v4.app.NotificationCompat;
导入android.util.Log;
导入android.widget.Toast;
公共类位置FetchInforeGround扩展服务{
私人传感器管理器传感器管理器;
专用传感器;
私有TriggerEventListener TriggerEventListener;
/**指示服务终止时的行为方式*/
int-mStartMode;
/**用于绑定的客户端的接口*/
朱鹭;
/**指示是否应使用onRebind*/
布尔mAllowRebind;
私有静态最终字符串TAG=“MyLocationService”;
私有位置管理器mLocationManager=null;
专用静态最终int位置_间隔=1000;
专用静态最终浮动位置_距离=0f;
私有类LocationListener实现android.location.LocationListener{
位置mLastLocation;
公共位置侦听器(字符串提供程序){
Log.e(标记“LocationListener”+提供者);
mLastLocation=新位置(提供商);
}
@凌驾
已更改位置上的公共无效(位置){
Log.e(标签“onLocationChanged:+位置);
Toast.makeText(getApplicationContext(),“onLocationUpdated”,Toast.LENGTH_LONG.show();
意图=新意图();
showNotification(getApplicationContext(),“位置已更改”,“位置已更新”,意图);
mLastLocation.set(位置);
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
Log.e(标记“onProviderDisabled:+提供程序”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
Log.e(标记“onProviderEnabled:+提供程序”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
Log.e(标记“onStatusChanged:+提供者”);
}
}
/*
LocationListener[]mlLocationListeners=新LocationListener[]{
新LocationListener(LocationManager.GPS_提供程序),
新LocationListener(LocationManager.NETWORK\u提供程序)
};
*/
LocationListener[]mlLocationListeners=新LocationListener[]{
新LocationListener(LocationManager.GPS\U提供程序)
};
/**在创建服务时调用*/
@凌驾
public void onCreate(){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
//用于创建前台服务
NotificationManager NotificationManager=(NotificationManager)getSystemService(通知服务);
字符串channelId=Build.VERSION.SDK\u INT>=Build.VERSION\u code.O?getNotificationChannel(notificationManager):“”;
NotificationCompat.Builder notificationBuilder=新建NotificationCompat.Builder(此为channelId);
Notification Notification=notificationBuilder.setContinuous(true)
.setContentTitle(“位置服务”)
.setContentText(“此服务用于获取后台位置”)
.setSmallIcon(R.mipmap.ic_启动器)
//.setPriority(优先级\最小值)
.setCategory(通知兼容CATEGORY_服务)
.build();
启动前(1,通知);
}
sensorManager=(sensorManager)getSystemService(Context.SENSOR\u服务);
sensor=sensorManager.getDefaultSensor(sensor.TYPE\u有效运动);
triggerEventListener=新triggerEventListener(){
@凌驾
公共无效onTrigger(触发事件){
//工作
Toast.makeText(getApplicationContext(),“位置更新”,Toast.LENGTH_LONG.show();
意图=新意图();
showNotification(getApplicationContext(),“运动更改”,“更新位置”,意图);
}
};
如果(传感器!=null){
sensorManager.requestTriggerSensor(triggerEventListener,传感器);
}
Log.e(标记为“onCreate”);
初始化ElocationManager();
}
/**由于调用startService()服务,服务正在启动*/
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
//让它继续运行直到停止。
Toast.makeText(此“服务已启动”,Toast.LENGTH_LONG).show();
试一试{
//Intent intenter=新Intent(这是LocationUpdatesReceiver.class);
//PendingEvent ProximityEvent=PendingEvent.getBroadcast(此,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.practice.satya.foreground">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-feature android:name="android.hardware.location.network"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".LocationFetchInForeground" />
        <receiver android:name=".LocationUpdatesReceiver"/>
    </application>

</manifest>