Android Timer dentro de un servicio

Tengo problemas para ejecutar un temporizador en un servicio que he creado. La tarea que el temporizador llama simplemente no se llama. Sé que el servicio comienza cuando he puesto tostadas dentro de él y se llaman, pero no cuando están dentro del contador de tiempo. Ayuda apreciada.

Clase de servicio

public class LocalService extends Service { private static Timer timer = new Timer(); private Context ctx; public IBinder onBind(Intent arg0) { return null; } public void onCreate() { super.onCreate(); ctx = this; startService(); } private void startService() { timer.scheduleAtFixedRate(new mainTask(), 0, 5000); } private class mainTask extends TimerTask { public void run() { Toast.makeText(ctx, "test", Toast.LENGTH_SHORT).show(); } } public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show(); } } 

Clase principal:

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startService(new Intent(RingerSchedule.this, LocalService.class)); } 

Android no permite eventos de interfaz de usuario como brindis desde fuera del hilo principal. La ejecución se está llamando, pero el brindis está siendo ignorado.

Para crear el Toast en el hilo de interfaz de usuario, puede utilizar un Handler y un mensaje vacío como el siguiente:

 public class LocalService extends Service { private static Timer timer = new Timer(); private Context ctx; public IBinder onBind(Intent arg0) { return null; } public void onCreate() { super.onCreate(); ctx = this; startService(); } private void startService() { timer.scheduleAtFixedRate(new mainTask(), 0, 5000); } private class mainTask extends TimerTask { public void run() { toastHandler.sendEmptyMessage(0); } } public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show(); } private final Handler toastHandler = new Handler() { @Override public void handleMessage(Message msg) { Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show(); } }; } 

Gracias, también necesitaba cancelar el temporizador ..

 public void onDestroy() { timer.cancel(); Toast.makeText(this, "ServiceTalkGeology stopped.", Toast.LENGTH_SHORT).show(); super.onDestroy(); } 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.