Android杀死由FCM消息启动的前台服务

时间:2019-12-21 09:32:04

标签: android firebase-cloud-messaging android-workmanager foreground-service

当收到来自FCM的数据通知时,我的应用程序启动了一项漫长的任务(例如上传文件)。这就是我通过启动前台服务做到的方式。它可以正常运行,但会在20秒后停止。

我在FCM doumenttation中读到我必须在收到邮件后20秒内(在Android棉花糖上为10秒)处理所有消息。好!我以为启动前台服务是对消息的一种响应,但事实并非如此!

我的代码中是否有错误会在几秒钟后停止?我可以通过从 foregroundService 切换到 Workmanager AlarmManager 等来克服此问题,并且它们是否算作对FCM消息的有效响应? / p>

这是我在FireBaseMessagingService中的代码:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {


    if (remoteMessage.getData() != null) {

        final String title = remoteMessage.getData().get("title");
        final String tag = remoteMessage.getData().get("tag");
        String body = remoteMessage.getData().get("body");

        Intent i = new Intent(this, Uploader.class);
        i.putExtra("title", title);
        i.putExtra("body", body);

        if (tag.equals("start")) {
            i.putExtra("act", "start");
        }

        if (tag.equals("stop")) {
            i.putExtra("act", "stop");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.startForegroundService(i);
        } else {
            this.startService(i);
        }
    }
}

这是上载程序类,它通过显示startForeground(1,mBuilder.build());通过显示粘性通知来启动前台;

public class Uploader extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String tag = intent.getStringExtra("act");
    String title = intent.getStringExtra("title");
    String body = intent.getStringExtra("body");
    showNotification(this,title,body,tag);
    return START_NOT_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public void showNotification(Context context, String title, String body, String tag) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    int notificationId = 1;
    String channelId = "channel-01";
    String channelName = "Channel Name";
    int importance = NotificationManager.IMPORTANCE_HIGH;

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId, channelName, importance);
        notificationManager.createNotificationChannel(mChannel);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(title)
            .setContentText(body);

    if (tag.equals("start")) {
        startForeground(1,mBuilder.build());
        startUploading();
    }
    if (tag.equals("stop")) {
        stopUploading();
    }
}

0 个答案:

没有答案