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"/> 
  • java.io.NotSerializableException al hacer clic en el botón de retroceso
  • Transmisión de datos entre varias actividades
  • Android Cómo llamar a OnFling cuando Swiping en cualquier lugar de la actividad no sólo en el ViewFlipper
  • ¿Cómo puede una Actividad acceder a un método de NotificationListenerService?
  • ¿Cómo abrir una nueva actividad haciendo clic en un elemento de listview?
  • ¿Cómo puedo ejecutar 2 actividades al mismo tiempo
  • Enviar ArrayList <Object> de BroadCastReceiver a Actividad
  • Fade in Actividad de la actividad anterior en Android
  • Inicie Actividad desde preferences.xml y obtenga el resultado en onActivityResult
  • OnCreate, onCreateOptionsMenu, onResume, ¿cuál es el orden de ejecución?
  • Android activity-reset después de tomar fotos (orientación?)
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.