从android远程服务每30分钟运行一次方法

问题描述:

我有一个在远程进程上运行的服务(通过AIDL接口)。这是一项不可阻挡的服务(从开机启动完成并持续到卸载应用程序为止)。该服务不断监听UDP套接字。我想每隔30分钟在这个服务中运行函数(负责通过udp socket向服务器发送ping消息)。从android远程服务每30分钟运行一次方法

我试图启动线程和睡眠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消息(我无法连接/绑定到广播接收器内的远程服务)

什么是最好的方法来克服我的问题?我可以在我的服务级别内使用闹钟管理器广播接收机吗(不使用单独的广播接收机级别)?

+0

在广播接收器开始为您服务,不与它结合,结合是不可能 – pskink

+0

都能跟得上我不想开始广播接收机内部服务,服务已经开始/运行(它是一种不可阻挡的服务)。我想连接到这个服务,以发送ping消息(ping消息通过服务发送) – eranga

+0

是的,我知道,唯一的方法是调用'startService'并在'onStartCommand'中得到通知,就像我说的你不能调用来自广播接收机的'bindService' – pskink

我为我的更新功能使用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); 
} 
+0

问题是我不能在一个单独的类中使用广播接收器,因为我在远程服务中使用了ping发送功能,如果在远程服务类中有一种使用广播接收器的方法,它将解决问题。 – eranga

+0

也许处理广播intents ?, http://*.com/questions/9128103/broadcastreceiver-with-multiple-filters-or-multiple-broadcastreceivers – Riksor