在服务中每隔5秒钟使用一个定时器,即接收方呼叫的服务

时间:2011-09-18 00:20:49

标签: android

我制作一个有效的接收器,这就是代码:

public class ServicioCargado extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i = new Intent();
            i.setAction("domain.androids.smsprojects.MyService");
            context.startService(i);
        }
    }

}

这是我的服务,它是由接收器创建的但是自动关闭,我不想要那个行为,我希望计时器继续运行,并且每5秒执行一次,我没有看到问题,谢谢所有

public class MyService extends Service {

    private MyService actual=null;

    private Timer timer = new Timer();
    private static final long UPDATE_INTERVAL = 5000;
    //private final IBinder mBinder = new MyBinder();

    @Override
    public IBinder onBind(Intent arg0) {
          return null;
    }
    @Override
    public void onCreate() {
          super.onCreate();
          //Hacemos un while que cada cierto tiempo haga algo o un sleep
          Toast.makeText(this,"Se esta ejecutando el programa para enviar sms", Toast.LENGTH_SHORT).show();
          actual=this;
          Log.d("Mauricio", "Creando servicio");
          Toast.makeText(this,"Antes de ejecutar el timer", Toast.LENGTH_SHORT).show();
          MyTimerExecution();
          Toast.makeText(this,"Despues de ejecutar el timer", Toast.LENGTH_SHORT).show();
        }

    private void MyTimerExecution() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // Imagine here a freaking cool web access ;-)
                //Toast.makeText(actual,"Service update ...", Toast.LENGTH_SHORT).show();
                Log.d("Mauricio","aqui");
            }
        }, 0, UPDATE_INTERVAL);
    }

    @Override
    public void onDestroy() {
          super.onDestroy();
          if (timer != null) {
            timer.cancel();
        }
        Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:1)

尝试使用Handler,在你真正想要的之后调用sendMessageDelayed(msg,UPDATE_INTERVAL)