简体   繁体   中英

Android service is not starting

I need to start a background service on click of android app icon. Below is my Activity oncreate() method.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_executable_runner);

    startService(new Intent(this, ExeRunnerService.class));
}

And this is my overridden service class rest all is the default.

public class ExeRunnerService extends Service{
    public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;

}
@Override
public void onCreate() {
    Thread th = new Thread(new Runnable() {
        public void run() {
            Log.d(TAG, "Service Running");
        }
    });
    th.start();

}
}

I don't have any initialization code for the same. But when I start the application I am not getting any service logs.

I would put and override on the onStartCommand, and call a super.onCreate() in the overridden onCreate method;

Like this:

public class MyService extends Service {
private static boolean isRunning = false;
private Context context;

@Override
public void onCreate() {
    super.onCreate();
    context = this;
}

public static boolean isServiceRunning() {
    return isRunning;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(!isRunning) {
      isRunning = true;

    }
    return START_STICKY;
}

Iv added the isRunning flag because I have often experienced that my service is already running and initializing objects again then is not a good idea.

Your service is calling but problem is with thread replace your code with following code in service's on create method

public void onCreate()
{
    Log.d("Run", "Service Running");
     new Thread(new Runnable()
    {

        public void run()
        {
            Log.d("Run", "Service Running");
        }
    }).start();;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM