是的。您的问题确实是由于设备内存不足。
当资源不足时,Android 会简单地处理正在运行的服务,例如您的服务。
接下来会发生什么取决于你
声明为粘性
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
将上述内容添加到您的服务将强制 Android 杀死后重新启动它,一旦资源
再上去。
如果正在运行的服务对您的系统至关重要,并且您不希望它在任何情况下自动终止
情况(提示:大多数时候这不是你想要的),你可以通过声明来做到这一点
它是一个前台服务
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("ticker text").setContentTitle("title text").setContentText("content")
.setWhen(System.currentTimeMillis()).setAutoCancel(false)
.setOngoing(true).setPriority(Notification.PRIORITY_HIGH)
.setContentIntent(pendIntent);
Notification notif = builder.build();
notif.flags |= Notification.FLAG_NO_CLEAR;
startForeground(NOTIF_ID, notif);
最后说明:IntentService 仅生成一个线程,所有请求都在该线程上执行。
这在许多情况下都可以正常工作。但是,当涉及到 IO-bound 执行时,您通常会得到
使用多个线程获得更好的性能。
所以,只有当性能是一个问题时,才考虑使用例如作业的多线程池:
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(
MIN_NUM_THREADS, MAX_NUM_THREADS, 10, TimeUnit.SECONDS, ...);
...
executorPool.execute(new MyWorkerThread(params));
ThreadPoolExecutor 构造函数接收的前两个参数设置最小值和最大值
并发活动线程数。