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:
- public class TestActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- startService(new Intent(this, TestService.class));
- }
- }
And the service class looks like this for instance:
- public class TestService extends Service{
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- }
-
- @Override
- public void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- }
-
- @Override
- public void onStart(Intent intent, int startId) {
- // TODO Auto-generated method stub
- super.onStart(intent, startId);
-
-
- public void run() {
-
- while(1 == 1){
- // do something useful and dont waste to much battery
- }
-
- }
- }).start();
- }
- }
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?


