create running background task within android

This is more of a beginners entry about that topic. Background tasks are called Service in Android. Creating and using one is pretty simple. From your activity call the following code:

  1. public class TestActivity extends Activity {
  2. @Override
  3. public void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.main);
  6.  
  7. startService(new Intent(this, TestService.class));
  8. }
  9. }

And the service class looks like this for instance:

  1. public class TestService extends Service{
  2. @Override
  3. public IBinder onBind(Intent intent) {
  4. return null;
  5. }
  6.  
  7. @Override
  8. public void onCreate() {
  9. // TODO Auto-generated method stub
  10. super.onCreate();
  11. }
  12.  
  13. @Override
  14. public void onDestroy() {
  15. // TODO Auto-generated method stub
  16. super.onDestroy();
  17. }
  18.  
  19. @Override
  20. public void onStart(Intent intent, int startId) {
  21. // TODO Auto-generated method stub
  22. super.onStart(intent, startId);
  23.  
  24. new Thread(new Runnable() {
  25.  
  26. public void run() {
  27.  
  28. while(1 == 1){
  29. // do something useful and dont waste to much battery
  30. }
  31.  
  32. }
  33. }).start();
  34. }
  35. }

Thats basically it, all you have to do now to make it work, is register that service within the AndroidManifest.xml with a line like that:

<service android:name=".package.TestService" />

Now you are done and got a background job running on your android device, again, easy, isn’t it?