Android:即使用户关闭了应用程序,也在后台运行线程

问题描述 投票:0回答:1

关闭应用后,我试图在后台向服务器发送http请求。但是线程总是被杀死。我已经尝试过Workmanager,AlarmManager和BackgroundService。在过去的几周里,我一直在互联网上寻找解决方案,但找不到在较新的API上运行且没有ForegroundService且在运行时必须显示通知的解决方案。

因为我已经尝试了很多,所以没有可以添加的特定代码。我期待着一个答案。

java android
1个回答
0
投票

您曾经尝试过ForegroundService吗?...您可以创建扩展为服务btw的类,只需在清单上添加意图过滤器即可。朋友班的例子。

public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    //do heavy work on a background thread


    //stopSelf();

    return START_NOT_STICKY;
}

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

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

并以startForegroundService(context,ForegroundService.class);

有很多选择(前台服务将启动通知,直到通知终止)

© www.soinside.com 2019 - 2024. All rights reserved.