java - Android:后台服务总是关闭

标签 java android service handler background-process

Android 后台任务运行行为的最新变化使得在手机锁定时保持服务 Activity 并继续在应用程序中工作变得非常困难。我的服务只有在屏幕亮起或手机充电时才能正常工作。当手机被锁定时,该服务几乎立即关闭或运行速度太慢而无法以任何方式使用。

我尝试使用“START_STICKY”标志和 startForeground() 通知来保持服务 Activity ,但这根本没有帮助。我使用的处理程序每​​ 5 秒调用一次 dowork(),然后检查是否有事情要做。

我想在某个时间事件上执行一个简单的任务:每半小时/刻钟或整小时醒来,做一些不受 CPU 限制的快速工作,然后关机直到下一次。手机应该按时可靠准确地唤醒,并进入“白名单”以使用一些 CPU 功率大约半分钟。我不做任何可能影响用户性能的高强度工作。

public class MyService extends Service {


public MyService() {
    super();

}


@Override
public IBinder onBind(Intent intent) {

    return null;
}

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

Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 通知 Intent ,0); 通知 notification = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("我的服务") .setContentText("服务正在运行") .setPriority(IMPORTANCE_HIGH) .setContentIntent(pendingIntent).build(); startForeground(1, 通知); 最终处理程序 handler = new Handler(); handler.postDelayed(new Runnable() { @覆盖 公共(public)无效运行(){ 做工作(); handler.postDelayed(this, 5000); } }, 1500); 返回START_STICKY; }

最佳答案

这个问题我想引用Alarm Manager Example .这个很好地完成了它的工作,我终于让它以这种方式工作。

关于java - Android:后台服务总是关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872894/

相关文章:

java - 如何在android studio中正确安装jdbc驱动?

android - 使用通用图像加载器保存本地恢复的图像

Android Service 多实例

java - Android 服务 OnStartCommand 不工作

java - Android 中的 SimpleDateFormat 在 Android 1.6 中提供不需要的时区

java - Android/Java 类范围和上下文

android - 正确的工作流程以从 Internet 检索数据并显示在 ListView 中

java - 下载管理器如何在 Android 上工作?

java - 如何在FXML Controller 中填充javafx.TableView?

java - java中不返回数组的ArrayList