Android Intent Service

Android Intent Service

Android intentService and BroadcastReceiver  is a a base class for Service that can be used to handle asynchronous work off the main thread by way of Intent requests on demand. Each intent is added to the IntentService’s queue and handled sequentially. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread — they may take as long as necessary (and will not block the application’s main loop), but only one request will be processed at a time.

Steps involved in implementing an Android IntentService example using BroadcastReceiver

  1. Create a class file that extends the IntentService class and add stubs for the methods you need to implement. You should add a constructor with the name of your new service. You will need to implement just one other method called onHandleIntent().
  2. In your Activity start the Service with a call to startService() for an Intent instance. You can pass any data to the intent using the extras. The service takes over from here, catching each intent request, processing it, and shutting itself down when it’s all done. The main user interface remains responsive throughout the processing, allowing the user to continue to interact with the application.
  3. You need to send a broadcast from the onHandleIntent() method of the IntentService class after the processing is complete to let the BroadcastReceiver know results of the process.
  4. Define the BroadcastReceiver as subclass within the main activity and register the receiver.

Step by step Tutorial:

Step 1 : Open the Android studio.

Step 2 :  Click on New Project option

Step 3 : This is called Configure your project where you gibe a name to your project and define you domain. Give the name of your application. (for example: IntentService).  Give the Company domain name or you can leave it as.  And give the project location.

 

Step 4.     After New Project Name Screen there come where you have to choose the particular android version. It implies/ tells us the compatibility of our project in different android platforms. To Study about Available Android Version Click here.

 

Step 5. In this part you have to select from the provided templates and the result project will be as similar that is displayed on the particular template as follows. It Act as the Main Class of this Project.

 

Here we Select the Empty Activity where we can do all the coding.

Step 6.        Give Activity Name, Layout Name, and title to selected Activity. In this I name It “IntentServieActivity” and the layout name as “main.xml” as well.

 

Step 7.        After you click on finish button on the last screen then the android will start to build the empty project for you. where you have to design your own layout and implement your own function. once finish it redirect us to the IntentServiceActivity.java page

 

Step8. working on main.xml for the designing part. here i add an EditText and textView when you click on image view then it redirect you to the phone call module where the predefined number has been dialed and call has started.

 

To run the app from Android studio, open one of your project’s activity files and click Run   icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window –

Here i use the android phone to run the project because Android Emulator takes so much time to process and sometimes it stuck in the process.

Codeing:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bonn.tempadmin.intentservices">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".IntentServiceActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

IntentServiceActivity.java

package com.bonn.tempadmin.intentservices;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class IntentServiceActivity extends AppCompatActivity {

    Button btnStart, btnSend;
    EditText editTextMsgToSend;
    TextView textViewCntReceived, textViewMsgReceived;

    MyMainReceiver myMainReceiver;
    Intent myIntent = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.startservice);
        btnSend = (Button)findViewById(R.id.send);
        editTextMsgToSend = (EditText)findViewById(R.id.msgtosend);
        textViewCntReceived = (TextView)findViewById(R.id.cntreceived);
        textViewMsgReceived = (TextView)findViewById(R.id.msgreceived);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService();
            }
        });

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msgToService = editTextMsgToSend.getText().toString();

                Intent intent = new Intent();
                intent.setAction(MyIntentService.ACTION_MSG_TO_SERVICE);
                intent.putExtra(MyIntentService.KEY_MSG_TO_SERVICE, msgToService);
                sendBroadcast(intent);
            }
        });
    }

    private void startService(){
        myIntent = new Intent(IntentServiceActivity.this, MyIntentService.class);
        startService(myIntent);
    }

    @Override
    protected void onStart() {
        myMainReceiver = new MyMainReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyIntentService.ACTION_UPDATE_CNT);
        intentFilter.addAction(MyIntentService.ACTION_UPDATE_MSG);
        registerReceiver(myMainReceiver, intentFilter);
        super.onStart();
    }

    @Override
    protected void onStop() {
        unregisterReceiver(myMainReceiver);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private class MyMainReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(MyIntentService.ACTION_UPDATE_CNT)){
                int int_from_service = intent.getIntExtra(MyIntentService.KEY_INT_FROM_SERVICE, 0);
                textViewCntReceived.setText(String.valueOf(int_from_service));
            }else if(action.equals(MyIntentService.ACTION_UPDATE_MSG)){
                String string_from_service = intent.getStringExtra(MyIntentService.KEY_STRING_FROM_SERVICE);
                textViewMsgReceived.setText(String.valueOf(string_from_service));
            }
        }
    }
}

MyIntentService.java

package com.bonn.tempadmin.intentservices;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Looper;
import android.widget.Toast;

public class MyIntentService extends IntentService {

    //from MyIntentService to MainActivity
    final static String KEY_INT_FROM_SERVICE = "KEY_INT_FROM_SERVICE";
    final static String KEY_STRING_FROM_SERVICE = "KEY_STRING_FROM_SERVICE";
    final static String ACTION_UPDATE_CNT = "UPDATE_CNT";
    final static String ACTION_UPDATE_MSG = "UPDATE_MSG";

    //from MainActivity to MyIntentService
    final static String KEY_MSG_TO_SERVICE = "KEY_MSG_TO_SERVICE";
    final static String ACTION_MSG_TO_SERVICE = "MSG_TO_SERVICE";

    MyServiceReceiver myServiceReceiver;
    int cnt;

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public void onCreate() {
        Toast.makeText(getApplicationContext(),
                "onCreate", Toast.LENGTH_LONG).show();
        myServiceReceiver = new MyServiceReceiver();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(),
                "onStartCommand", Toast.LENGTH_LONG).show();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_MSG_TO_SERVICE);
        registerReceiver(myServiceReceiver, intentFilter);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(),
                "onDestroy", Toast.LENGTH_LONG).show();
        unregisterReceiver(myServiceReceiver);
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String prompt;
        //check if current thread is Main Thread (UI)
        if(Looper.myLooper() == Looper.getMainLooper()){
            prompt = "onHandleIntent run in UI Thread";
        }else{
            prompt = "onHandleIntent run in NOT UI Thread";
        }

        Intent iPrompt = new Intent();
        iPrompt.setAction(ACTION_UPDATE_MSG);
        iPrompt.putExtra(KEY_STRING_FROM_SERVICE, prompt);
        sendBroadcast(iPrompt);

        cnt = 10;
        while (cnt >= 0){
            try {
                Thread.sleep(1000);

                Intent i = new Intent();
                i.setAction(ACTION_UPDATE_CNT);
                i.putExtra(KEY_INT_FROM_SERVICE, cnt);
                sendBroadcast(i);

                cnt--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public class MyServiceReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(action.equals(ACTION_MSG_TO_SERVICE)){
                String msg = intent.getStringExtra(KEY_MSG_TO_SERVICE);

                msg = new StringBuilder(msg).reverse().toString();

                //send back to MainActivity
                Intent i = new Intent();
                i.setAction(ACTION_UPDATE_MSG);
                i.putExtra(KEY_STRING_FROM_SERVICE, msg);
                sendBroadcast(i);
            }
        }
    }

}

Main.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context=".IntentServiceActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://wintechturorials.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/startservice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"/>
    <EditText
        android:id="@+id/msgtosend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="msg to send..." />
    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send msg to service"/>
    <TextView
        android:id="@+id/cntreceived"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="26dp"/>
    <TextView
        android:id="@+id/msgreceived"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textStyle="bold"
        android:textSize="20dp"/>

</LinearLayout>

Output:

 

Post a comment

Your email address will not be published. Required fields are marked *