Iniciar o serviço no Android

Quero chamar um serviço quando uma determinada actividade começar. Então, aqui está a aula de serviço:

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

e aqui está como eu lhe chamo:

Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);
O problema é que nada acontece. O bloco de código acima é chamado no final da Atividade onCreate. Já depurei e não há excepção.

Alguma ideia?

Author: Peter Mortensen, 2011-01-22

4 answers

Provavelmente não tem o serviço no seu manifesto, ou não tem um <intent-filter> que corresponda à sua acção. Examinar o LogCat (via adb logcat, DDMS ou a perspectiva DDMS no Eclipse) deve mostrar alguns avisos que podem ajudar.

É mais provável que comece o serviço através de:

startService(new Intent(this, UpdaterServiceManager.class));
 241
Author: CommonsWare, 2011-01-22 02:19:05
startService(new Intent(this, MyService.class));
Apenas escrever esta linha não foi suficiente para mim. O serviço ainda não funcionou. Tudo tinha funcionado apenas depois de registar o serviço na manifest
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>
 73
Author: Vitalii Korsakov, 2012-09-23 19:01:45

Código Java para iniciar serviço:

Iniciar o serviço a partir de actividade:

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

Iniciar o serviço a partir de fragmento:

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

Meu serviço.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 serviço no ficheiro manifesto do projecto:

Adicionar abaixo da marca no manifesto ficheiro:

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

Concluído

 45
Author: Hiren Patel, 2015-09-10 03:51:52
Gosto de o tornar mais dinâmico.
Class<?> serviceMonitor = MyService.class; 


private void startMyService() { context.startService(new Intent(context, serviceMonitor)); }
private void stopMyService()  { context.stopService(new Intent(context, serviceMonitor));  }
Não te esqueças do Manifesto.
<service android:enabled="true" android:name=".MyService.class" />
 2
Author: Joolah, 2015-06-15 04:53:03