2013-08-16 163 views
0

我已经开发了一项服务,在活动启动时自动启动。 但我想停止一定的时间间隔说10秒后服务,并在30秒后说一段时间后再次启动服务。 我是一个新的android编程,所以没有得到如何做到这一点,请帮助。 我正在使用广播接收器来启动服务。延迟启动服务

+0

使用报警管理 –

+0

可能重复[如何安排一些代码执行在Android或:?究竟是Android的守护线程(http://stackoverflow.com/questions/3883246/how- to-schedule-some-code-execution-in-android-or-what-exactly-are-daemon-threa) – Gusdor

+0

使用TimerTask或AlarmManager – AndroUser

回答

5

我会建议使用报警管理器和发送挂起的意图来启动服务。就像这样:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
Intent serviceIntent = new Intent(context, ServiceReceiver.class); 
PendingIntent pi = PendingIntent.getBroadcast(context, ServiceIdsConstants.SERVICE_ID,  serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT); 
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, pi); 

然后在广播接收器做到这一点:

Intent intent = new Intent(context, MyServiceService.class); 
context.startService(intent); 
+0

使用wifimanager和bluetoothmanager时可以使用闹钟管理器吗? – user2661237

+0

我不确定我是否按照你的问题。一般来说,广播接收器没有很多时间来执行。你通常会从他们开始一项服务。然后使用服务上下文,您可以获得蓝牙或WiFi管理器。 –

+0

是否有任何理由直接使用am.getBroadcast(serviceIntent)而不是直接使用am.getService(MyServiceService),完全绕过广播? – averasko

0

只是写了一个实用工具,您和其他人可以使用:

public static void startDelayedWakefulService(Context context,long delayInMillis,Class<? extends Service> serviceClass) { 
    AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    Intent serviceIntent = new Intent(context, DelayedStartServiceBroadcastReceiver.class); 
    serviceIntent.putExtra("className",serviceClass.getName()); 
    PendingIntent pi= PendingIntent.getBroadcast(context, 7, serviceIntent , PendingIntent.FLAG_UPDATE_CURRENT); 
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeInMillis()+delayInMillis, pi); 
} 

public class DelayedStartServiceBroadcastReceiver extends WakefulBroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     String className = intent.getStringExtra("className"); 
     try { 
      startWakefulService(context,new Intent(context,Class.forName(className))); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
      completeWakefulIntent(intent); 
     } 
    } 
} 

不要忘记将它添加到您的清单

<receiver 
     android:name=".utils.DelayedStartServiceBroadcastReceiver" 
     android:enabled="true" 
     android:exported="true" > 
    </receiver>