126

I want to call a service when a certain activity starts. So, here's the Service class:

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

And here is how I call it:

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

The problem is that nothing happens. The above code block is called at the end of the activity's onCreate. I already debugged and no exception is thrown.

Any idea?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Miguel Ribeiro
  • 8,057
  • 20
  • 51
  • 74
  • 1
    Careful with Timers - AFAIK when your service is shut down to free resources this timer will not be restarted when service is restarted. You're right ```START_STICKY``` will restart the service, but then only onCreate is called and the timer var will not be re-initialized. You can play with ```START_REDELIVER_INTENT```, the Alarm service or the API 21 Job Scheduler to fix this. – Georg Jan 12 '15 at 22:24
  • 1
    In case you have forgotten, ensure you have registered the service in the android manifest using `` within the application tag. – Japheth Ongeri - inkalimeva Sep 09 '16 at 13:22

5 Answers5

298

Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    How you can debugg ? never called my service, my debugg not show nothing –  Nov 09 '15 at 23:04
  • Add a shitton of Log.e tags everywhere: Before you launch the service, the result of the service intent, inside the service class where it would travel(onCreate, onDestroy, any and all methods). – Zoe Apr 10 '17 at 18:41
  • it's work for my apps on android sdk 26+ but dose not on android sdk 25 or lower. there have any solution ? – Mahidul Islam Mar 12 '18 at 07:29
  • @MahidulIslam: I recommend that you ask a separate Stack Overflow question, where you can provide a [mcve] explaining your problem and symptoms in greater detail. – CommonsWare Mar 12 '18 at 10:27
  • @CommonsWare i already asked a question and that's :- https://stackoverflow.com/questions/49232627/android-apps-crash-when-excute-startservice-on-sdk-25-and-lower – Mahidul Islam Mar 12 '18 at 10:30
88
startService(new Intent(this, MyService.class));

Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest

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

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>
Vitalii Korsakov
  • 45,737
  • 20
  • 72
  • 90
  • 1
    Best example to learn everything regarding services in Android http://coderzpassion.com/implement-service-android/ and sorry for being late – Jagjit Singh Jun 28 '17 at 05:19
  • 1
    My search for automation ended here. Used Manifest as well as startService in my App and it works like a charm. Thank you!! – Sriram Nadiminti Dec 12 '20 at 09:20
56

Java code for start service:

Start service from Activity:

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

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

}

Define this Service into Project's Manifest File:

Add below tag in Manifest file:

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

Done

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
4

I like to make it more dynamic

Class<?> serviceMonitor = MyService.class; 


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

do not forget the Manifest

<service android:enabled="true" android:name=".MyService.class" />
Thiago
  • 12,778
  • 14
  • 93
  • 110
2
Intent serviceIntent = new Intent(this,YourActivity.class);

startService(serviceIntent);

add service in manifist

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

for running service on oreo and greater devices use for ground service and show notification to user

or use geofencing service for location update in background reference http://stackoverflow.com/questions/tagged/google-play-services

Asif Mehmood
  • 141
  • 1
  • 14