从活动中调用后台服务 [英] Calling background Service from an Activity

查看:144
本文介绍了从活动中调用后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动和后台服务。我通过从活动意图启动该服务。该服务将无限期运行,即使该活动已关闭。但这里的问题是,如果我明确从任务管理器中存储的服务站,并没有再次启动,直到活动再次启动。我希望该服务一段时间后内存被清除自动启动。我怎么能做到这一点?请大家帮帮忙。

解决方案

  AlarmManager服务=(AlarmManager)getApplicationContext()。getSystemService(
                Context.ALARM_SERVICE);
            意图I =新的意图(这一点,BackgroundService.class);
            日历CAL = Calendar.getInstance();
            cal.add(Calendar.SECOND,30);
            PendingIntent未决= PendingIntent.getService(此,0,I,
                PendingIntent.FLAG_CANCEL_CURRENT);
            service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),30000,待定);
 

这code是运行backgroundService真正的30000毫秒

I have an Activity and a background Service. I start the Service via Intent from the Activity. The Service runs indefinitely even if the Activity is closed. But the problem here is if I clear the memory from the Task manager the Service stops and is not started again untill the Activity is launched again. I want the Service to start automatically after some time the memory is cleared. How could I achieve this? Please help.

解决方案

AlarmManager service = (AlarmManager) getApplicationContext().getSystemService(
                Context.ALARM_SERVICE);
            Intent i = new Intent(this, BackgroundService.class);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 30);
            PendingIntent pending = PendingIntent.getService(this, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
            service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),30000, pending);

this code is true 30000 miliseconds run backgroundService

这篇关于从活动中调用后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆