Avvia il servizio in Android


115

Voglio chiamare un servizio quando inizia una determinata attività. Quindi, ecco la classe Service:

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();
    }
}

Ed ecco come lo chiamo:

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

Il problema è che non succede niente. Il blocco di codice sopra viene chiamato alla fine dell'attività onCreate. Ho già eseguito il debug e non viene generata alcuna eccezione.

Qualche idea?


1
Attenzione ai timer - AFAIK quando il servizio viene arrestato per liberare risorse, questo timer non verrà riavviato quando il servizio viene riavviato. Hai ragione START_STICKYriavvierà il servizio, ma poi verrà chiamato solo onCreate e il timer var non verrà reinizializzato. Puoi giocare con START_REDELIVER_INTENT, il servizio di allarme o l'API 21 Job Scheduler per risolvere questo problema.
Georg,

In caso di dimenticanza, assicurati di aver registrato il servizio nel manifest di Android utilizzando <service android:name="your.package.name.here.ServiceClass" />il tag dell'applicazione.
Japheth Ongeri - inkalimeva,

Risposte:


278

Probabilmente non hai il servizio nel tuo manifest, o non ha un <intent-filter>che corrisponde alla tua azione. L'esame di LogCat (tramite adb logcat, DDMS o la prospettiva DDMS in Eclipse) dovrebbe visualizzare alcuni avvisi che potrebbero essere utili.

Più probabilmente, dovresti avviare il servizio tramite:

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

1
Come puoi eseguire il debug? mai chiamato il mio servizio, il mio debugg non mostra nulla
consegna il

Aggiungi un po 'di tag Log.e ovunque: prima di avviare il servizio, il risultato dell'intento del servizio, all'interno della classe del servizio in cui viaggerebbe (onCreate, onDestroy, tutti i metodi).
Zoe

funziona per le mie app su Android SDK 26+ ma non su Android SDK 25 o inferiore. c'è qualche soluzione?
Mahidul Islam

@ MahidulIslam: ti consiglio di porre una domanda separata su Stack Overflow, in cui puoi fornire un esempio riproducibile minimo che spiega il tuo problema e i tuoi sintomi in modo più dettagliato.
CommonsWare

@CommonsWare Ho già fatto una domanda e questo è: - stackoverflow.com/questions/49232627/...
Mahidul Islam

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

Il solo fatto di scrivere questa riga non è stato sufficiente per me. Il servizio continuava a non funzionare. Tutto aveva funzionato solo dopo la registrazione al servizio di manifest

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

    ...

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

1
Il miglior esempio per imparare tutto ciò che riguarda i servizi in Android coderzpassion.com/implement-service-android e scusa per il ritardo
Jagjit Singh

55

Codice Java per avviare il servizio :

Avvia servizio da attività :

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

Avvia il servizio da Fragment :

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

}

Definisci questo servizio nel file manifest del progetto:

Aggiungi sotto il tag nel file Manifest :

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

Fatto


7
Quanto migliora le prestazioni quando lascio attività e servizi nello stesso pacchetto? Mai sentito prima.
OneWorld

Forse intendevano prestazioni in un senso molto vago, non sulla velocità di corsa?
Anubian Noob

3

Mi piace renderlo più dinamico

Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }

non dimenticare il manifesto

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

1
Intent serviceIntent = new Intent(this,YourActivity.class);

startService(serviceIntent);

aggiungi servizio in manifist

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

per eseguire il servizio su oreo e dispositivi superiori utilizzare per il servizio a terra e mostrare la notifica all'utente

oppure utilizza il servizio di geofencing per l'aggiornamento della posizione come riferimento in background http://stackoverflow.com/questions/tagged/google-play-services

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.