【发布时间】:2019-04-26 16:03:45
【问题描述】:
我正在运行前台服务,当应用程序从最近的应用程序托盘中删除时,它的通知消失了。 即使从最近的应用程序托盘关闭应用程序,我也想将数据从数据库发送到服务器。我怎样才能做到这一点?
显示通知的代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand executed");
context = AppController.getInstance().getApplicationContext();
if (intent.getAction().equals("com.truiton.foregroundservice.action.startforeground")) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction("com.truiton.foregroundservice.action.main");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ConnectivityCheckReceiver.class);
previousIntent.setAction("com.truiton.foregroundservice.action.prev");
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Truiton Music Player")
.setTicker("Truiton Music Player")
.setContentText("My Music")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.addAction(android.R.drawable.ic_media_previous,
"Previous", ppreviousIntent)
.build();
startForeground(101,
notification);
}
return START_STICKY;
}
【问题讨论】:
-
显示相关代码
-
@fillobotto 我已经编辑了我的问题以添加代码。
-
整个代码应该放在
onCreate服务方法中 -
向服务器发送数据的代码在哪里写?
-
您应该使用
onCreate仅用于通知构建和startForeground。其余的服务逻辑保持不变。您仍然可以调用服务并在onStartCommand中详细说明意图
标签: android foreground-service