Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday, 23 May 2016

IntentService Example

Hello friends
Today we are learn about how to use IntentService in your app.

actvity_main.xml


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="IntentService and BroadcastReceiver Example"
        android:textSize="16sp"
        android:paddingTop="20dp" />

    <Button
        android:layout_gravity="center"
        android:text="Send Request"
        android:id="@+id/sendRequest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:id="@+id/linearLayout1"
        android:layout_height="wrap_content">

        <TextView
            android:text="Response Url"
            android:layout_height="wrap_content"
            android:id="@+id/textView1"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="wrap_content"
            android:paddingTop="25dp" />

        <TextView android:text=""
            android:layout_height="wrap_content"
            android:id="@+id/response"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="wrap_content"
            android:layout_marginLeft="10dp" />

    </LinearLayout>

    <WebView
        android:layout_width="match_parent"
        android:id="@+id/myWebView"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java


package com.samset.intentservicesample;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class MyActivity extends Activity {

    MyBroadcastReciver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter filter = new IntentFilter(MyIntentService.PROCESS_RESPONSE);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new MyBroadcastReciver();
        registerReceiver(receiver, filter);

        Button addButton = (Button) findViewById(R.id.sendRequest);
        addButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Intent msgIntent = new Intent(MyActivity.this, MyIntentService.class);

                msgIntent.putExtra(MyIntentService.REQUEST_STRING, "http://www.amazon.com");
                startService(msgIntent);

                msgIntent.putExtra(MyIntentService.REQUEST_STRING, "https://github.com/SamsetDev?tab=repositories");
                startService(msgIntent);

                msgIntent.putExtra(MyIntentService.REQUEST_STRING, "http://samsetdev.blogspot.in/");
                startService(msgIntent);
            }
        });
    }

    @Override
    public void onDestroy() {
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }
    class MyBroadcastReciver extends BroadcastReceiver
    {

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

            String responseString = intent.getStringExtra(MyIntentService.RESPONSE_STRING);
            String reponseMessage = intent.getStringExtra(MyIntentService.RESPONSE_MESSAGE);

            TextView myTextView = (TextView) findViewById(R.id.response);
            myTextView.setText(responseString);

            WebView myWebView = (WebView) findViewById(R.id.myWebView);
            myWebView.getSettings().setJavaScriptEnabled(true);
            try {
                myWebView.loadData(URLEncoder.encode(reponseMessage,"utf-8").replaceAll("\\+"," "), "text/html", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
    }
}

MyIntentService.java


package com.samset.intentservicesample;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by weesync on 23/05/16.
 */
public class MyIntentService extends IntentService {

    public static final String REQUEST_STRING = "myRequest";
    public static final String RESPONSE_STRING = "myResponse";
    public static final String RESPONSE_MESSAGE = "myResponseMessage";

    private String URL = null;
    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    public static final String PROCESS_RESPONSE = "com.samset.intentservicesample.intent.action.PROCESS_RESPONSE";

    private static OkHttpClient okHttpClient;
    private static String strdata;

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


    @Override
    protected void onHandleIntent(Intent intent) {
        String requestString = intent.getStringExtra(REQUEST_STRING);
        String responseString = requestString + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());

        SystemClock.sleep(10000); // Wait 10 seconds
       
Log.v("MyWebRequestService:", responseString);
        String output = getDataFromserver(requestString);
        broadcastData(responseString, output);


    }

    private void broadcastData(String data, String msg) {

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(PROCESS_RESPONSE);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        broadcastIntent.putExtra(RESPONSE_STRING, data);
        broadcastIntent.putExtra(RESPONSE_MESSAGE, msg);
        sendBroadcast(broadcastIntent);
    }

    public static String getDataFromserver(String url) {
        okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        Response response = null;

        try {
            response = okHttpClient.newCall(request).execute();
            strdata = response.body().string();


        } catch (IOException e) {
            e.printStackTrace();
        }
        return strdata;
    }

}

AndroidMainifest.xml


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

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

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

        <!-- Declaring Service in Manifest -->
     
<service
          android:name=".MyIntentService"
          android:exported="false"/>
    </application>

</manifest>

build.gradle


apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

   
defaultConfig {
        applicationId "com.samset.intentservicesample"
       
minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
   
}
    buildTypes {
        release {
            minifyEnabled false
           
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
       
}
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
   
compile 'com.android.support:appcompat-v7:23.3.0'
   
compile 'com.squareup.okhttp:okhttp:2.4.0'
   
compile 'com.squareup.picasso:picasso:2.5.2'
}

thank you

FullSourceCode IntentServiceSample


Live Sample