【问题标题】:Run method in every 30 minutes from android remote service从android远程服务每30分钟运行一次方法
【发布时间】:2016-02-05 05:58:03
【问题描述】:

我有一个在远程进程上运行的服务(通过 AIDL 接口)。这是一项不可阻挡的服务(在启动完成时开始并持续到卸载应用程序)。该服务一直在监听 UDP 套接字。我想每 30 分钟在该服务中运行一次功能(负责通过 udp 套接字向服务器发送 ping 消息)。

我尝试启动线程并休眠 30 分钟,但没有成功

new Thread(new Runnable() {
    public void run() {
        while (true) {
            try {
                sendPingMessage();
                Thread.currentThread().sleep(1000 * 60 * 30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}).start();

这个函数在任意时间内调用。不完全是在 30 分钟内。

还尝试了定时器任务、处理程序和ScheduledExecutorService,也没有运气

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate (new Runnable() {
    public void run() {
        sendPingMessage();
    }
}, 0, 30, TimeUnit.MINUTES);

似乎问题出在 android 深度睡眠模式 [http://binarybuffer.com/2012/07/executing-scheduled-periodic-tasks-in-android][1]

我也尝试过使用 AlarmManger。但是我不能在单独的班级中使用广播接收器作为警报管理器。由于我想从 android 远程服务发送 ping 消息(我无法连接/绑定到广播接收器内的远程服务)

解决我的问题的最佳方法是什么?我可以在我的服务类中使用警报管理器广播接收器(不使用单独的广播接收器类)吗?

【问题讨论】:

  • 在你的广播接收器中启动你的服务,不要绑定它,绑定是不可能的
  • 不,我不想在广播接收器中启动服务,服务已经启动/运行(它是一个不可停止的服务)。我想连接到该服务以发送 ping 消息(通过该服务发送 ping 消息)
  • 是的,我知道,唯一的方法是致电startService 并在onStartCommand 中获得通知,正如我所说,您不能从广播接收器中致电bindService

标签: android multithreading scheduled-tasks android-handler aidl


【解决方案1】:

我将 AlarmManager 用于我的更新功能。也许这也适合你。

void updatecheck(Context context){

    Intent alarmIntent = new Intent(context, yourclass.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 30 * 60 * 1000, pendingIntent);
}

【讨论】:

  • 问题是我不能在单独的类中使用广播接收器,因为我的 ping 发送功能在远程服务中,如果有办法在我的远程服务类中使用广播接收器,它将解决问题。
  • 也许正在处理广播意图?,stackoverflow.com/questions/9128103/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多