【问题标题】:Android Run Process in BackgroundAndroid 在后台运行进程
【发布时间】:2016-02-17 01:58:17
【问题描述】:

我正在制作一个使用 BroadcastReceiver 和 WakefulServiceIntent 的应用程序,每 10 分钟在我的应用程序中调用一个方法。问题是,有时它会调用它,有时它不会。我需要每 10 分钟调用一次此方法,即使应用程序正在后台运行或屏幕已关闭。我当前的代码如下。我不应该使用 AlarmManager 来启动计时器吗?我听说 AlarmManager 不准确,但不准确到它甚至不会响的地方?

AlarmManager 启动代码:

    Intent intent = new Intent(getContext(), UpdateReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + ((2 * 60) * 1000)), ((10 * 60) * 1000), pendingIntent);

BroadcastReceiver 类:

public class UpdateReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent service = new Intent(context, UpdateService.class);

        startWakefulService(context, service);

    }

}

WakefulIntentService 类:

public class UpdateService extends IntentService {

    public UpdateService() {

        super("UpdateService");

    }

    @Override
    protected void onHandleIntent(Intent intent) {

        System.out.println("updated automatically");

        OverviewFragment.refresh(getApplicationContext());

        UpdateReceiver.completeWakefulIntent(intent);

    }

}

【问题讨论】:

    标签: android android-intentservice android-broadcastreceiver


    【解决方案1】:

    我在三星旗舰智能手机上开发后台服务和闹钟计划事件方面拥有丰富的经验。

    您可以尝试禁用所有组件的电池优化,但即便如此,操作系统也不会可靠地调用您的代码。

    在我的书中,这是一个错误,但我确信三星和/或 Google 认为它是一项功能(资源管理绝对是他们的首要任务)。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      相关资源
      最近更新 更多