我想我的应用程序在后台运行并未被Android关闭

问题描述:

我的应用程序有一个服务,每30秒执行一次特定URL的获取。该服务使在AndroidManifest.xml配置:我想我的应用程序在后台运行并未被Android关闭

<receiver 
    android:name="com.analisesistemas.taxiweb.android.alarm.MyAlarmReceiver" 
    android:process=":remote" > 
</receiver> 
<service 
    android:name="com.suporte.motoweb.chegaja.MyTestService" 
    android:exported="false" /> 

服务由我的应用程序启动时这样说:

// Setup a recurring alarm every half minute 
public void scheduleAlarm() { 
// Construct an intent that will execute the AlarmReceiver 
Intent intent = new Intent(getApplicationContext(), MyAlarmReceiver.class); 

// Create a PendingIntent to be triggered when the alarm goes off 
final PendingIntent pIntent = PendingIntent.getBroadcast(this, MyAlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

// Setup periodic alarm every 5 seconds 
long firstMillis = System.currentTimeMillis(); // alarm is set right away 

AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 

// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP 
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY 
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, TIMER, pIntent); 
} 

的方法scheduleAlarm()被调用在我的主要活动的onCreate()。

问题是,当我按Home键(以最小化我的应用程序),所以我可以使用其他应用程序,如Facebook和Instagram ...我注意到我的应用程序停止运行(android关闭我的应用程序可能会节省内存)。

真的,我已经尝试了各种方式,但Android在后台运行时关闭了我的应用程序。不是马上,它是几分钟后!

我该如何防止我的应用程序被Android操作系统终止?我需要让它无限期地运行! :(

感谢自从关注

+0

每30秒发出一次GET请求将导致数据使用量过大和电量耗尽,这将导致所有用户卸载您的应用。详细说明你正在尝试解决的问题,我可以给你一个更好的解决方案,以便如何最好地解决它https://developer.android.com/training/efficient-downloads/index.html –

+0

这种行为可能是ROM的依赖,而不是Android(通常)的依赖。我记得在4.0.1中有一个类似的错误,如果我记得正确的话,但是它在很久以前就已经在更高版本中被修复了。 –

根据您的要求,而不是粘服务,我会建议你使用GCM Network Manager它采用JobSchedular API的棒棒糖,并针对Android,以及更低的版本上的版本和类似兼容的方式。对于周期性任务会为你做所有困难的步骤,你可以主要集中在商业逻辑。

PeriodicTask task = new PeriodicTask.Builder() 
     .setService(MyTaskService.class) 
     .setTag(TASK_TAG_PERIODIC) 
     .setPeriod(30L) 
     .build(); 

mGcmNetworkManager.schedule(task); 

你可以的onDestroy发送广播()服务的方法,而当你接收广播

启动服务
+0

嗨,我该怎么做?你有一个例子吗? – user2725921

+0

对不起,这只是一个想法。但我不认为这很困难。由于阻止系统停止应用程序很困难,因此可以在应用程序停止时重新启动。当服务停止时,它必须运行ondestroy(),因此您可以使用ondestroy()方法发送广播,并在接收停止广播时注册启动服务的广播接收器 –

你认为每30秒设置一次http请求是个好主意吗?正如@JustinSlade所提到的,这将导致手机过度使用电池和糟糕的用户体验。

此外,目前尚不清楚有什么不对您当前的机制 - 从先来看看AlarmManager应该触发BroadcastReceiver,其中,据我了解运行Service那里请求被执行(和,也许,重新安排报警)。那么,这里有什么问题?你没有收到广播的意图吗?

无论如何,这是非常丑陋的方法,我建议你使用Google Cloud Messaging,并且只有在新数据可用时才通知应用程序。为了提高申请流程的优先级,您还可以在Service中使用setForeground,但这需要在通知面板中提供UI。