Reputation: 580
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.
Upvotes: 0
Views: 93
Reputation: 949
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.
Upvotes: 1
Reputation:
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();;
}
Upvotes: 0