Wednesday 25 December 2013

IntentService with WebService Example




activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="getData"
        android:text="get data" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>


MyWebService.java:
package com.ram.intentservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.IntentService;
import android.content.Intent;

public class MyWebService extends IntentService {

    public MyWebService() {
        super("DownloadService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.cheesejedi.com/rest_services/get_big_cheese.php?puzzle=");

        try {

            HttpResponse response = httpclient.execute(httppost);
            String jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();

            if (jsonResult != null) {
                sendResultBroadcast(jsonResult);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader rd = new BufferedReader(isr);

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

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

    void sendResultBroadcast(String jsonResult) {
        Intent in = new Intent();

        in.putExtra("jsonresult", jsonResult);

        in.setAction("com.ram.CUSTOM_BROADCAST");

        sendBroadcast(in);
    }
}






MainActivity.java:

package com.ram.intentservice;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView textView;
    ProgressDialog pd;

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

        registerReceiver(new WebServiceBroadcast(), new IntentFilter(
                "com.ram.CUSTOM_BROADCAST"));

        textView = (TextView) findViewById(R.id.textView);

    }

    public void getData(View v) {
        pd = ProgressDialog.show(MainActivity.this, "loading", "plz wait");

        Intent intentService = new Intent(getApplicationContext(),
                MyWebService.class);
        startService(intentService);
    }

    class WebServiceBroadcast extends BroadcastReceiver {

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

            pd.cancel();

            String jsonResult = intent.getStringExtra("jsonresult");

            JSONArray jsonArray = null;

            try {
                jsonArray = new JSONArray(jsonResult);

                for (int i = 0; i < jsonArray.length(); i++) {

                    textView.append("id: "
                            + jsonArray.getJSONObject(i).getString("id")
                                    .toString() + "\n");

                    textView.append("level: "
                            + jsonArray.getJSONObject(i).getString("level")
                                    .toString() + "\n");
                    textView.append("time_in_secs: "
                            + jsonArray.getJSONObject(i)
                                    .getString("time_in_secs").toString()
                            + "\n");
                    textView.append("par: "
                            + jsonArray.getJSONObject(i).getString("par")
                                    .toString() + "\n");
                    textView.append("initials: "
                            + jsonArray.getJSONObject(i).getString("initials")
                                    .toString() + "\n");
                    textView.append("quote: "
                            + jsonArray.getJSONObject(i).getString("quote")
                                    .toString() + "\n");
                    textView.append("time_stamp: "
                            + jsonArray.getJSONObject(i)
                                    .getString("time_stamp").toString() + "\n");
                    textView.append("" + "\n");

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
}



AndroidManifest.xml:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ram.intentservice.MainActivity"
            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="MyWebService"></service>
    </application>

</manifest>
 


No comments:

Post a Comment