Android How to - Put long-running service to a separate Thread








The service runs on the same thread as your activity.

For a long-running service, it is important that you put all long-running code into a separate thread so that it does not tie up the application that calls it.

The following code shows how to Put long-running service to a separate Thread.

Example

Populate the MyService.java file with the following code:

package com.java2s.myapplication3.app;
//from  w  ww.  ja  v  a  2s .c o  m
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            new DoBackgroundTask().execute(new URL("http://www.java2s.net/somefiles.pdf"));

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    private int DownloadFile(URL url) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 100;
    }

    private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
        protected Long doInBackground(URL... urls) {
            int count = urls.length;
            long totalBytesDownloaded = 0;
            for (int i = 0; i < count; i++) {
                totalBytesDownloaded += DownloadFile(urls[i]);
                publishProgress((int) (((i+1) / (float) count) * 100));
            }
            return totalBytesDownloaded;
        }

        protected void onProgressUpdate(Integer... progress) {
            Toast.makeText (getBaseContext(),String.valueOf(progress[0]) + "% downloaded",Toast.LENGTH_LONG).show();
        }

        protected void onPostExecute(Long result) {
            Toast.makeText (getBaseContext(),
                    "Downloaded " + result + " bytes",
                    Toast.LENGTH_LONG).show();
            stopSelf();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText (this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

In the AndroidManifest.xml file, add the following statement:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.java2s.Services"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
         android:label="@string/app_name"
         android:name=".ServicesActivity" >
         <intent-filter >
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <service android:name=".MyService" />
 </application>

</manifest>

Main layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Service"
    android:onClick="startService"/>

<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Stop Service"
    android:onClick="stopService" />

</LinearLayout>

Main Activity Java code

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
//from  ww w.  ja  va 2 s .c o  m
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void startService(View view) {
           startService(new Intent(getBaseContext(), MyService.class));
    }

    public void stopService(View view) {
       stopService(new Intent(getBaseContext(),MyService.class));
    }
}




Note

Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.