2011-01-22 27 views
93

Deseo llamar a un servicio cuando se inicia cierta actividad. Por lo tanto, aquí está la clase de servicio:Servicio de inicio en Android

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 así es como yo 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 depuré y no se lanza ninguna excepción.

¿Alguna idea?

+1

Cuidado con contadores de tiempo - que yo sepa cuando su servicio se cierra para liberar recursos este temporizador no se reiniciará cuando se reinicie el servicio.Tiene razón: '' 'START_STICKY'' reiniciará el servicio, pero solo se llamará a onCreate y no se reinicializará el temporizador var. Puede jugar con '' 'START_REDELIVER_INTENT''', el servicio de alarma o el Programador de tareas API 21 para solucionar esto. – georg

+0

En caso de que lo haya olvidado, asegúrese de haber registrado el servicio en el manifiesto de Android usando '' dentro de la etiqueta de la aplicación. –

Respuesta

227

Probablemente no tenga 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 aparecer algunas advertencias que pueden ser útiles.

Lo más probable es que usted debe iniciar el servicio a través de:

startService(new Intent(this, UpdaterServiceManager.class)); 
+0

¿Cómo se puede depurar? nunca llamé a mi servicio, mi depuración no muestra nada – delive

+0

Agregue una cantidad de etiquetas Log.e en todas partes: antes de iniciar el servicio, el resultado de la intención del servicio, dentro de la clase de servicio donde viajaría (onCreate, onDestroy, cualquiera) métodos). – Zoe

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

Sólo escribir esta línea no era suficiente para mí. El servicio aún no funcionó. Todo había trabajado solamente después de registrar el servicio en manifiesta

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" > 

    ... 

    <service 
     android:name=".MyService" 
     android:label="My Service" > 
    </service> 
</application> 
+1

El mejor ejemplo para aprender todo sobre los servicios en Android http://coderzpassion.com/implement-service-android/ y disculpa por llegar tarde –

42

código Java para inicioservicio:

servicio de inicio de Actividad:

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

servicio de inicio de 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"); 
    } 

} 

Definir este servicio en archivo de manifiesto de Proyecto:

Añadir a continuación la etiqueta en Manifiesto archivo:

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

Hecho

+7

¿Cuánto mejora el rendimiento cuando dejo actividades y servicios en el mismo paquete? Nunca escuché eso antes. – OneWorld

+0

Quizás se referían al rendimiento en un sentido muy impreciso, ¿no se trata de velocidad de funcionamiento? –

2

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 se olvide el Manifiesto

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

activty: startService(new Intent(this,ChatService.class));

Manifiesto -

<service 
    android:name=.ChatService" 
    android:enabled="true" 
    android:process=":ChatProcess"/> 
Cuestiones relacionadas