Search This Blog

Sunday, 29 April 2012

Service example in android

Service is one of core component of android application. Every one knows service is very important part. we use it but sometimes we do not know exact power and depth of service, today i am going to discuss it in details.
After this article we will also let you know difference between Thread and Service, and how to perform real time task in service


In the end you will also get source code.

Service -A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

Difference between a Thread , service and asynchronous task

1)  Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

2)  A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

3)  An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components

Other one difference between service and thread is that thread is not intelligent enough to recognize that is it already running or not? Every time you create a new object of thread and start again it will create a new instance and a new thread start running.
But if service is already running and you start again it will not created again.So that is very important difference



Step to create simple service example

Step 1) create a a new project. change your xml to include two button to start and stop service


<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StartService" 
        android:id="@+id/start"/>
    
        <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StopService"
        android:id="@+id/stop" />

</LinearLayout>

Step 2) create  a new class to create service. and extends service in this class

package com.demo;

import java.util.Random;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ServiceExample extends Service {

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

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"Service Created",300);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Destroy",300);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Toast.makeText(this,"Service LowMemory",300);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"Service start",300);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        
        Toast.makeText(this,"task perform in service",300);
        ThreadDemo td=new ThreadDemo();
        td.start();
        return super.onStartCommand(intent, flags, startId);
    }
    
    private class ThreadDemo extends Thread{
        @Override
        public void run() {
            super.run();
            try{
            sleep(70*1000);    
            handler.sendEmptyMessage(0);
            }catch(Exception e){
                e.getMessage();
            }
        }
    }
   private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //showAppNotification();
    }
   };
}





service onCreate() called only once when service first started then other method followed by it. In onstarteCommand() i started a thread to do some background task. after completion of thread you can give a notification to user that task has been completed. For this i have taken a Handler

Now we will take an activity to show user inter face for starting service



package com.demo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class ServiceDemoActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
    }

    private Intent inetnt;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:
            
            inetnt=new Intent(this,ServiceExample.class);
            startService(inetnt);
            break;
        case R.id.stop:
            
            inetnt=new Intent(this,ServiceExample.class);
            stopService(inetnt);
            break;
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        
    }
}

service can be started in two way Context.startService() and Context.bindService(). second option is  used to bind service with activity or something else in this case we unbind service when activity destroy 

Enjoy and play with my code by downloading it and mention service in manifest inside application tag like


<service android:name=".ServiceExample"/>


4 comments:

  1. this will not work. Services have no context (you can't use "this") and services cannot access UI (you can't use Toast).

    ReplyDelete
  2. Did you check it Ever?? It work dude i posted it after checking, It shows Toast perfectly using context of Service. By Default service contain its parent activity context who started this. Once check agin.

    ReplyDelete

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code