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:
- ¿Cómo programar tematicamente una actividad para ser como un diálogo?
- Mostrar vista en toda mi aplicación
- Diapositiva xml animación en la actividad de cambio en android
- ¿Cómo puede una aplicación de Android tener cero actividades
- ¿Cómo establezco la actividad principal de una actividad en tiempo de ejecución?
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?
- NullPointerException en findViewById () en android
- Restauración del estado en Android cuando se utiliza el botón "arriba"
- ¿Cuándo ocurre onCreateOptionsMenu en una actividad activada con ActionBar?
- Actualización de la actividad TextView desde el servicio mediante vinculación de servicio
- ¿Cuál es la diferencia exacta entre onAttachedToWindow y onStart
- Indicador de configuración en onSaveInstanceState () para determinar tipo de salida en onDestroy ()
- Cómo llamar a un método en otra actividad
- Actualización de textview en la actividad una vez que se cambian los datos en la clase de adaptador
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"/>
- TextInputLayout no muestra la sugerencia de EditText antes de que el usuario se centre en ella
- La etiqueta languageLevel de Android .idea / misc.xml sigue cambiando JDKs