Monday 24 September 2012

Different Types of Started Service


Different Types of Started Service:
       1.       Normal Service without  Thread.
       2.       Service with Single Thread
       3.       Service with Multithreading
       4.       Service with Multithreading (ASYNC TASK)


Normal Service Without Thread:
          1.    Create service tag in your manifest.xml file.
          2.    Implement life cycle function for your service.
          3.    Start your service from your activity and make sure your service will stop.
Example:

Manifest.xml
For developing any service , you need to include service tag in your manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tara.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
   <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
                                <service android:name="MyService"></service>
    </application>
</manifest>


Main.xml 
Create a button in main.xml. When you click the button, service will start.
<?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/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>



MyActivity.java

public class MyActivity extends Activity
{
         Intent it = new Intent(this, MyService.class);
    public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener()
{             
public void onClick(View v)
                                                {             
                                                   startService(it);             
                                                }
                                });
    }
    protected void onDestroy()
    {         
          stopService(it);
    }


MyService.java
public class MyService extends Service
{
                @Override
                public void onCreate()
                {
                                super.onCreate();
                }
                @Override
                public int onStartCommand(Intent intent, int flags, int startId)
                {
                                return super.onStartCommand(intent, flags, startId);
                }
                @Override
                public void onDestroy()
                {             
                                super.onDestroy();
                }
                @Override
                public IBinder onBind(Intent intent)
                {
                                return null;
                }
}


Service With Single Thread:

In service with single thread, you can manually create a thread. You need to use IntentService class, thread will be created automatically.
       1.    Create service tag in your manifest.xml file. Provide the class name (MyService.java). It will extends from IntentService. Then add the un-implemented method.
       2.    Start your service from your activity and make sure your service will stop.

Manifest.xml

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

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

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

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

</manifest>

MyService.java

public class MyService extends IntentService
{

                public MyService(String name) {
                                super(name);
                                // TODO Auto-generated constructor stub
                }

                @Override
                protected void onHandleIntent(Intent arg0) {
                                // TODO Auto-generated method stub
                               
                }

}

Here you can’t touch UI beacause onHandleIntent() is running on different thread created by IntentService.


Service With MultiThreading (ASYNC-TASK):

AsyncTask has 4 operations, which are executed by order.

1. onPreExecute() – is invoked before the execution.
2. onPostExecute() - is invoked after the execution.
3. doInBackground() - the main operation. Write your heavy operation here.
4. onProgressUpdate() – Indication to the user on progress. It is invoked every time 
publishProgress() is called.


AsyncTask defines 3 generic types:
AsyncTask<{type of the input}, {type of the update unit}, {type of the result}>
You don’t have to use all of them – simply use ‘Void’ for any of them.


Android developer website also mentions these 4 rules regarding the AsyncTask:
§  The task instance must be created on the UI thread.
§  execute(Params…) must be invoked on the UI thread.
§  Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params…), onProgressUpdate(Progress…) manually.
§  The task can be executed only once (an exception will be thrown if a second execution is attempted.)

The Service class will look like this:

MyService.java

public class MyService extends Service
{
                @Override
                public void onCreate()
                {
                super.onCreate();
                }


                public class MyTask extends AsyncTask<Void, Integer, String>
                {
                                protected void onPreExecute()
                                {
                                                super.onPreExecute();
                                }
                                protected String doInBackground(Void... params)
                                {
                                                return null;
                                }
                                protected void onProgressUpdate(Integer... values)
                                {
                                                super.onProgressUpdate(values);
                                }
                                protected void onPostExecute(String result)
                                {
                                                super.onPostExecute(result);
                                }
                }

               
                @Override
                public int onStartCommand(Intent intent, int flags, int startId)
                {
                return super.onStartCommand(intent, flags, startId);
                }
                @Override
                public void onDestroy()
                {
                                super.onDestroy();
                }
                @Override
                public IBinder onBind(Intent intent) {
                                // TODO Auto-generated method stub
                                return null;
                }
               
}

No comments:

Post a Comment