Iniciar servicio en Android

Quiero llamar a un servicio cuando comienza una determinada actividad. Así que aquí está la clase de servicio:

public class UpdaterServiceManager extends Service { private final int UPDATE_INTERVAL = 60 * 1000; private Timer timer = new Timer(); private static final int NOTIFICATION_EX = 1; private NotificationManager notificationManager; public UpdaterServiceManager() {} @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // Code to execute when the service is first created } @Override public void onDestroy() { if (timer != null) { timer.cancel(); } } @Override public int onStartCommand(Intent intent, int flags, int startid) { notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = android.R.drawable.stat_notify_sync; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(this, Main.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notificationManager.notify(NOTIFICATION_EX, notification); Toast.makeText(this, "Started!", Toast.LENGTH_LONG); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Check if there are updates here and notify if true } }, 0, UPDATE_INTERVAL); return START_STICKY; } private void stopService() { if (timer != null) timer.cancel(); } } 

Y aquí es cómo lo llamo:

 Intent serviceIntent = new Intent(); serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager"); startService(serviceIntent); 

El problema es que no pasa nada. El bloque de código anterior se llama al final de la actividad onCreate . Ya he depurado y no se produce ninguna excepción.

¿Alguna idea?

Probablemente no tiene el servicio en su manifiesto, o no tiene un <intent-filter> que coincida con su acción. Examinar LogCat (a través de adb logcat , DDMS o la perspectiva de DDMS en Eclipse) debería mostrar algunas advertencias que pueden ayudar.

Lo más probable es que comience el servicio a través de:

 startService(new Intent(this, UpdaterServiceManager.class)); 
 startService(new Intent(this, MyService.class)); 

Sólo escribir esta línea no era suficiente para mí. El servicio todavía no funcionaba. Todo había funcionado sólo después de registrar el servicio en el manifiesto

 <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > ... <service android:name=".MyService" android:label="My Service" > </service> </application> 

Código Java para el servicio de inicio :

Iniciar servicio de Actividad :

 startService(new Intent(MyActivity.this, MyService.class)); 

Iniciar servicio desde Fragmento :

 getActivity().startService(new Intent(getActivity(), MyService.class)); 

MyService.java :

 import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.util.Log; public class MyService extends Service { private static String TAG = "MyService"; private Handler handler; private Runnable runnable; private final int runTime = 5000; @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate"); handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(runnable, runTime); } }; handler.post(runnable); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { if (handler != null) { handler.removeCallbacks(runnable); } super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @SuppressWarnings("deprecation") @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.i(TAG, "onStart"); } } 

Defina este servicio en el archivo de manifiesto del proyecto:

Añada la etiqueta a continuación en el archivo del manifiesto :

 <service android:enabled="true" android:name="com.my.packagename.MyService" /> 

Hecho

Me gusta hacerlo más dinámico

 Class<?> serviceMonitor = MyService.class; private void startMyService() { context.startService(new Intent(context, serviceMonitor)); } private void stopMyService() { context.stopService(new Intent(context, serviceMonitor)); } 

No olvide el Manifiesto

 <service android:enabled="true" android:name=".MyService.class" /> 

Activty: startService (new Intent (esto, ChatService.class));

Manifiesto –

  <service android:name=.ChatService" android:enabled="true" android:process=":ChatProcess"/> 
  • ¿Cómo terminar la actividad de los padres de la actividad infantil sin terminar / detener la actividad infantil?
  • Android Master / Detalle de flujo dentro de ViewPager
  • Cómo pasar datos de la escena Unity a la actividad de Android
  • Actividad inicial de Android-Library-Project
  • Lista de todas las actividades de la aplicación
  • Lanzar Skype desde una aplicación mediante programación y número de pase - Android
  • Android listview desaparece después de la rotación de la pantalla
  • Requerir una contraseña antes de deshabilitar la aplicación como administrador en Android
  • IllegalArgumentException: No se puede cambiar el tipo de ventana después de agregar la ventana
  • ¿Cuál es el punto de `Content_main.xml`?
  • Determine si la actividad se adelantó debido a la navegación posterior
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.