欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

后台定时任务(从开机起,开启一个app级HTTP服务器)

程序员文章站 2022-05-01 19:16:37
接收广播:里面开启一个服务LongRunningService;接收开机广播,也接收LongRunningService发出的广播。public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(FaceApplication.getCont...

接收广播:

里面开启一个服务LongRunningService;

接收开机广播,也接收LongRunningService发出的广播。

 public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(FaceApplication.getContext(), LongRunningService.class);
        i.putExtra("type",1);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(i);
        } else {
            context.startService(i);
        }
    }
} 

被开启的服务:

里面每5s发送一广播给AlarmReceiver

里面开线程执行自己想要干的任务(开启一个HTTP服务器)

 public class LongRunningService extends Service {
    private MyAppServer mywebserver;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int type = intent.getIntExtra("type",1)

本文地址:https://blog.csdn.net/ningchao328/article/details/107790215