我创建了一个跟踪设备移动位置的服务.该服务由绑定到它的Activity启动,在此活动中有一个"开始跟踪"按钮.按下此按钮时,我需要服务在前台启动,以便它存储设备已移动到的位置,即使绑定到它的活动已关闭,或应用程序已最小化.
我知道,要使服务位于前台,必须显示通知.我试图这样做,但是当活动被销毁时,我无法获得显示通知或服务在前台工作.
由于通知渠道,Oreo的通知似乎已经发生变化,但我无法弄清楚需要采取哪些不同的措施.我正在测试它的设备是8.0.0.
这是mys服务:
public class LocationTrackerService extends Service {
private LocationListener locationListener;
private LocationManager locationManager;
private IBinder binder = new LocalBinder();
private boolean isTracking;
private ArrayList<Location> trackedWaypoints;
private String bestProvider;
private Timer timer;
private Distance distance;
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, true);
isTracking = false;
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent intent = new Intent("location_update");
intent.putExtra("latitude", location.getLatitude());
intent.putExtra("longitude", location.getLongitude()); …Run Code Online (Sandbox Code Playgroud) android foreground android-service android-notifications foregroundnotification