Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to work with services and intents in Android Applications

In this article we will see the process of working with the services and intents in Android Application and will see the difference between service and activity.

In many application of Android, developer is faced with the following problem: how to launch another GUI activity from the currently running one. A famous example for this is to launch home screen activity after some configurable duration has passed in the Welcome screen. Usually the welcome screen is dedicated to view the APP name for a moment, and then the main home screen is launched.

Another situation that faces Android developer is the need to handle some calculations or processing to be done in the back ground of the application, because the user GUI thread must be kept highly responsive, hence, the heavy calculations must be done in the back ground to keep the GUI responsive. In this case, the developer needs not only to launch a sub GUI activity, but also needs a separate back ground thread to do his offline calculations.

Intents are created in Android for this purpose. Intents are classes that have the activity life cycle defined (created, running, suspended, killed,….etc). Intents usually operate on a certain Context. Intents can take one of two forms: activity or service. An activity runs on the same thread as GUI, while the service runs by default on different back ground thread to keep the GUI thread responsive. Two ways to activate an Intent exist: starting a service (startService) and starting an activity (startActivity). Starting an activity is just to start another GUI activity (home and welcome screen examples), while starting a service is to start a back ground thread, different than GUI thread, to handle back ground calculations and to keep GUI thread responsive.

It is reasonable that values need to be passed between activities and services. For example, some keys might need to be passed to the back ground service to do the heavy calculations on it. Android provides a way to pass values between activity and sub-activities and services and each others, using the getExtras().putExtra method, which takes the key name (string) and its value. This passed value can be recovered when the intent is handled (being it service or activity). The value is recovered by getExtras().getInt, getByte, getChar,…etc according to the type of info passed by the main activity or service.

Sub activity or service is a special action that needs to be defined in the AndroindManifest.xml file. The main application activity is defined in the manifest file by the <activity> tag. Similarly, any other sub-activity must be also defined by the <activity> tag as well, otherwise a run time error shall occur. Similarly any service to be launched in background must be also defined in the AndroindManifest.xml file using the <service> tag. For <activity> or <service> tags, the most important parameter to be defined is the “android:name” parameter. This name parameter defines the name of the class to be used to handle this activity or service. Otherwise a run time error shall occur and the application stops working immediately.

Difference between service and activity

A service is a class that extends the Android class android.app.Service. It represents a kind of Context. A class that implements a service handler should run the thread of the service. By default, the service thread is independent and different from the GUI thread.

The handler implementation should like the code below. Two methods need to be overridden from the base Service class: onBind and onStart. Whatever you write inside onStart() shall be executed every time the service is entered. The name of the class “ServiceHandler” shall be used later in two places, when creating the intent that starts the service, and when defining the service in the AndoridManifest.xml file.

Listing 1: In the example below, the code just shows a Toast message when the service is started saying “Service is handled” for short period “Toast.LENGTH_SHORT”.

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

public class ServiceHandler extends Service  
{


   @Override
   public IBinder onBind(Intent intent) {
      // TODO Auto-generated method stub
      return null;
   }
   
   @Override
   public void onStart(Intent intent, int startId) {
      // TODO Auto-generated method stub
      super.onStart(intent, startId);
      Toast.makeText(this.getBaseContext(), "Service Handled", Toast.LENGTH_SHORT).show();
   }

}

On the other hand, an Activity class is a GUI thread context. It represents the main execution GUI of the application. Any class that implements an Activity must implement the interface class “andoriod.app.Activity” The example below shows the basic way to implement an Activity. The onCreate method must be implemented. Every time the activity is invoked, the onCreate() method is invoked as well, and whatever code you write here is executed. Usually the main task to do in onCreate is to inflate the GUI view. The view is usually defined in an xml layout file. The setContentView() method is used to set the Activity main view to the xml layout file we design for this activity.

Listing 2: In the example below, our xml layout is called main.xml, hence setContentView sets it from the resource class to be the main layout file.

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


public class SubActivity extends Activity {
    private Button returnBotton;

   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Listing 3: The structure of main.xml layout of the sub-activity is shown below. It consists of a TextView and a Button.

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello2" />

    <Button
        android:id="@+id/returnButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Return" />
    


</LinearLayout>

Manifest file creation

To use a sub-activity in your application, you need to define it in the AndroidManifest.xml file.

The full implementation is shown below. The AndroidManifest.xml file in this example has 2 activities which are: the main activity ".TestIntentActivity" and the sub-activity ".SubActivity" . The sub-activity is launched from within the main activity. Notice the difference in fields mandatory for both cases. Both the main and sub activities require to fill <activity> attribute parameters. However, for the main activity the <intent-filter> attribute is needed to define the type of the action: "android.intent.action.MAIN" and the category: "android.intent.category.LAUNCHER" .

This name parameter defines the name of the class to be used to handle this activity. Otherwise a run time error shall occur and the application stops working immediately.

Listing 4: For both cases the most important parameter to be defined is the “android:name” parameter.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mine.testintent"
    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=".TestIntentActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity
          android:name=".SubActivity"
          android:label="@string/app_name2" >
      </activity>
    </application>

</manifest>

For the service case, it’s a bit different. The parameter <service> needs to be filled. The most important parameter to be defined is the “android:name” parameter.

Otherwise a run time error shall occur and the application stops working immediately.

Listing 5: This name parameter defines the name of the class to be used to handle this service.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mine.testprojects.com"
    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=".TestStartServiceActivity"
            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="ServiceHandler2"></service>
    </application>

</manifest>

Starting sub-activity

To start an activity from a main activity, first you need to create an intent object giving it the current context and the class name that handles the activity (which must implement the activity interface as discussed above). startActivity method can then be used to launch the sub-activity taking the intent object just formed.

Listing 6: The example below shows that. It launches the sub-activity when a button is clicked.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class TestIntentActivity extends Activity {
    private Button launchBotton;

   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       
       launchBotton = (Button)findViewById(R.id.launchButton);
       
       launchBotton.setOnClickListener(new View.OnClickListener() 
                               {
                              
                                 @Override
                                 public void onClick(View v) 
                                 {
                                    // TODO Auto-generated method stub
                                     Intent subActivity = new Intent(TestIntentActivity.this, SubActivity.class);
                                                                      
                                     startActivity(subActivity);
                                    
                                 }
                               }
                              );
       
    }
}

Starting service

Starting a back ground service is just similar to the sub-activity case. Again, an intent object needs to be filled in the same way and passed to startService method this time.

The intent object is created on the fly inside the call to startService method.

Listing 7: The example below shows an activity that starts a service handled by ServiceHandler2 class.

 
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class TestStartServiceActivity extends Activity 
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startService(new Intent(this, ServiceHandler2.class));
        
    }
}

Passing values to sub-service or activity

It is reasonable that values need to be passed between activities and services. For example, some keys might need to be passed to the back ground service to do the heavy calculations on it. Android provides a way to pass values between activity and sub-activities and services and each others, using the getExtras().putExtra method, which takes the key name (string) and its value. This passed value can be recovered when the intent is handled (being it service or activity).

Listing 8: The value is recovered by getExtras().getInt, getByte, getChar,…etc according to the type of info passed by the main activity or service.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class TestIntentActivity extends Activity {
    private Button launchBotton;

   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       
       launchBotton = (Button)findViewById(R.id.launchButton);
       
       launchBotton.setOnClickListener(new View.OnClickListener() 
                               {
                              
                                 @Override
                                 public void onClick(View v) 
                                 {
                                    // TODO Auto-generated method stub
                                     Intent subActivity = new Intent(TestIntentActivity.this, SubActivity.class);
                                     
                                     subActivity.putExtra("key_id", 10);
                                     
                                     startActivity(subActivity);
                                    
                                 }
                               }
                              );
       

       
    }
}


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

// This sub-activity should also be added to AndroidManifest.xml
public class SubActivity extends Activity {
    private Button returnBotton;

   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        
        Bundle extras = getIntent().getExtras();
        int x = extras.getInt("key_id");
        
        
        Toast msg = Toast.makeText(this, String.valueOf(x) , Toast.LENGTH_LONG);
        
        msg.setGravity(Gravity.CENTER , msg.getXOffset()/2 , msg.getYOffset()/2);
        
        msg.show();
        
        returnBotton = (Button)findViewById(R.id.returnButton);
        
        returnBotton.setOnClickListener(new View.OnClickListener() {
         
         @Override
         public void onClick(View v) {
            // TODO Auto-generated method stub
              // Return back to original context
              Intent origActivity = new Intent(SubActivity.this, TestIntentActivity.class);
              startActivity(origActivity);
            
         }
      });
        
    }
}

Delayed activity launch

When a home screen needs to be launched after welcome screen, a small period is needed in between to let the welcome screen static for a while.

Listing 9: This is achieved by using the timer class as in the example below. It creates a new scheduled timer task to run after DURATION which is just a constant to be defined in your code.

 new Timer().schedule(new TimerTask()
        {
			
			@Override
			public void run() 
			{
				// Start the home screen
				//finish activity doesn't work
				//WelcomeActivity.this.finishActivity(0);//Add in manifest file: android:noHistory="true" after android:name=".WelcomeActivity"
				startActivity(new Intent(WelcomeActivity.this, HomeActivity.class));
			}
		}, DURATION);

Conclusion

In this tutorial we learnt the different between service and activity and their usages, how to start each. Also we learnt how to define them in the manifest file. Finally we learnt how to make delayed run of a service or activity after a while using the timer scheduler.



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login