I'm trying to create a simple service that prints to the logs every few seconds, even when the app is back grounded, and although I've researched this, I'm still bemused as to how I could do it. I'd really appreciate it if someone could show me a bit of code that I could use to do this.
Asked
Active
Viewed 57 times
2 Answers
0
ServiceClass.java (IntentService starts on a new thread, we do not need to create a new thread in it.)
public class IntentServiceDemo extends IntentService {
int currentState=0;
public IntentServiceDemo() {
super("IntentServiceDemoWorker"); // super the name of worker thread, it is necessary.
}
@Override
protected void onHandleIntent(Intent intent) {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
++currentState:
Log.d("vabhi", "currentState : " + currentState);
} // End of while
}
}
Mainifest (inside application tag)
<service android:name=".IntentServiceDemo" android:exported="false"></service>
inside MainActivity.java
public void startIntentService(View v)
{
Intent intent = new Intent(MainActivity.this,IntentServiceDemo.class);
startService(intent);
}

vabhi vab
- 419
- 4
- 11