当应用程序从后台托盘关闭时,前台服务不会保留

时间:2018-03-08 10:33:27

标签: android foreground-service

我正在运行前台服务,当应用程序从最近的应用程序托盘中删除时,其通知消失。 即使应用程序从最近的应用程序托盘关闭,我也希望将数据从数据库发送到服务器。我怎样才能做到这一点?

显示通知的代码:

@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;
}

1 个答案:

答案 0 :(得分:0)

为每个持久性前台服务/通知创建单独的服务

Android清单:

<service android:directBootAware="true"
    android:enabled="true"
    android:exported="true"
    android:name=".ForegroundService1">
    . . .
</service>

您的服务类别:

public class ForegroundService1 extends android.app.Service
{
    static final int foregroundID = 1234567;
    static final string channelID = "Sync notification";
    ...

    @override
    public int onStartCommand(Intent intent, int flags, int startId) {
    {
        Notification notification = new NotificationCompat.Builder(this, channelID)
                                                  .setContentTitle("Syncing ...")
                                                  .setContentText("Some more text")
                                                  .setSmallIcon(Resource.Drawable.my_notification)
                                                  .setOngoing(true)
                                                  .setAutoCancel(false)
                                                  .build();

        //If Build >= Android Oreo
        //Create notification channel for channelID
        //@see https://developer.android.com/training/notify-user/channels#CreateChannel

        startForeground(foregroundID, notification);

        //Create Handler on separate thread, run your sync inside runnable
        HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
        handlerThread.start();
        Looper looper = handlerThread.getLooper();
        Handler handler = new Handler(looper);
        handler.post(new Runnable() {
            @Override  
            public void run() {
                StartSync();
            }
        });

        return Service.START_STICKY;
    }

    private void StartSync()
    {
        //Your code here which runs for a long while..

        //After you are done, stop the service and foreground notification
        stopForeground(true);
        stopSelf();
    }
}

开始

Intent i = new Intent(context, ForegroundService1.class);
android.support.v4.content.ContextCompat.StartForegroundService(context, i);