【发布时间】:2018-10-01 03:22:48
【问题描述】:
将手机升级到 8.1 Developer Preview 后,我的后台服务无法正常启动。我仍然看到差异,在 android oreo 中我没有看到我的自定义前台通知(我只看到“应用程序正在后台运行”通知)。它也适用于 android
我的服务:
public class ForegroundService extends Service {
private static final String LOG_TAG = "ForegroundService";
public static boolean IS_SERVICE_RUNNING = false;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
showNotification();
} else if (intent != null && intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
MainActivity.exoPlayer.setPlayWhenReady(false);
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.radio);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Background")
.setContentText("is Playing...")
.setSmallIcon(R.drawable.background)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(android.R.drawable.ic_delete, "Turn Off",
pplayIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// Used only in case if services are bound (Bound Services).
return null;
}
}
我的常数:
public class Constants {
public interface ACTION {
public static String MAIN_ACTION = "com.marothiatechs.foregroundservice.action.main";
public static String PLAY_ACTION = "com.marothiatechs.foregroundservice.action.play";
public static String STARTFOREGROUND_ACTION = "com.marothiatechs.foregroundservice.action.startforeground";
public static String STOPFOREGROUND_ACTION = "com.marothiatechs.foregroundservice.action.stopforeground";
}
public interface NOTIFICATION_ID {
public static int FOREGROUND_SERVICE = 101;
}
}
【问题讨论】:
-
你的
targetSdkVersion是什么? -
stackoverflow.com/a/52490432/6541643希望这个答案对你有帮助:)
标签: android service android-notifications android-8.0-oreo foreground-service