我正在开发一个Android应用程序,我正在启动一个无限期运行的后台服务,但运行得很好但是在做了一些研究之后,似乎我应该将它添加为前台服务,以便它具有被杀的可能性更小。即使应用程序关闭或被杀,我也希望此服务继续在后台运行。将前台服务添加到我的服务类之后,我注意到当你拉下通知栏时,手机会冻结并且屏幕会在显示备份之前擦除空白几秒钟。通知栏在加载后按计划工作,但它占用的时间太长。我对服务很新,但我开始更好地掌握它们,所以任何帮助都非常感谢。一直在运行Anodrid 5.1.1的One Plus Two手机上进行测试。这是我的应用设置:
MainActivity.java
@Override
public void onClick(View v) {
switch (v.getId()) {
Intent serviceIntent = new Intent(this, MileageService.class);
serviceIntent.setAction("start");
startService(serviceIntent);
Intent i = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(i);
}
}
MileageService.java
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Everything under here before the final return START_STICKY
//was newly added and is the source of the new issues
if (intent.getAction().equals("start")) {
if(stringNames.size() == 0) {
subscribeToLocationUpdates();
Intent stopIntent = new Intent(this, MileageService.class);
stopIntent.setAction("stop");
PendingIntent pStopIntent = PendingIntent.getService(this, 0, stopIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_name);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Mileage Service")
.setTicker("Mileage Service")
.setContentText("Mileage service is running")
.setSmallIcon(R.drawable.android_logo)
.setLargeIcon(icon)
.setOngoing(true)
.addAction(R.drawable.ic_media_pause, "Stop", pStopIntent).build();
startForeground(101, notification);
}else{
return START_STICKY;
}
} else if (intent.getAction().equals("stop")) {
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
public void onLocationChanged(final Location loc) {
Log.i("***********", "Location changed");
//I also do code here that updates global variables
//that get put into an intent to be sent back to app in further
//activities but not showing it as it works fine before adding
//notification foreground code
intent.putExtra("names", stringNames);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}