Tuesday, May 26, 2015

ANDROID : IntentService Example

IntentService is a base class for Service  that handle asynchronous requests on demand. 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.



Here I am implemeted a IntentService , wich download the html data of http://www.facebook.com and http://www.google.com




Step 1 : Add the service to AndroidManifest.xml file






Step 2 : Create MyIntentService.java file

package com.raspberry.demo.sample;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

import com.google.android.gms.internal.u;

import java.io.IOException;
import java.net.URL;

public class MyIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_DOWNLOAD_GOOGLE = "com.raspberry.demo.download.Google";
    private static final String ACTION_DOWNLOAD_FACEBOOK = "com.raspberry.demo.download.Facebook";



    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startDownloadGoogle(Context context) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_DOWNLOAD_GOOGLE);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startDownloadFacebook(Context context) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_DOWNLOAD_FACEBOOK);
        context.startService(intent);
    }

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

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("onHandleIntent" , "onHandleIntent");
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_DOWNLOAD_GOOGLE.equals(action)) {
                handleDownloadGoogle();
            } else if (ACTION_DOWNLOAD_FACEBOOK.equals(action)) {
                handleDownloadFacebook();
            }
        }
    }

    /**
     * Handle action DownloadGoogle
     *
     * Will executed in separate worker thread
     *
     */
    private void handleDownloadGoogle() {

        URLProcessor urlProcessor = new SlaveResponseimpl();
        try {
            urlProcessor.process(new URL("http://www.google.com"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Handle action DownloadFacebook
     *
     * Will executed in separate worker thread
     *
     */
    private void handleDownloadFacebook() {


        URLProcessor urlProcessor = new SlaveResponseimpl();
        try {
            urlProcessor.process(new URL("http://www.facebook.com"));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}



How to start the service

The Service can started by using startDownloadGoogle or startDownloadFacebook functions in the MyIntentService class.

eg :

MyIntentService.startDownloadFacebook(getApplicationContext());
MyIntentService.startDownloadGoogle(getApplicationContext())


Helper classes to download HTML from url

URLProcessor.java
package com.example.cybrosys.sample;

import java.io.IOException;
import java.net.URL;


public interface URLProcessor {
 public void process(URL url) throws IOException; 
}


URLProcessorBase.java


package com.example.cybrosys.sample;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public abstract class URLProcessorBase implements URLProcessor {

 public void process(URL url) throws IOException {
        URLConnection urlConnection = url.openConnection();
        InputStream input = urlConnection.getInputStream();

        try{
            processURLData(input);
        } finally {
            input.close();
        }
    }

    protected abstract void processURLData(InputStream input)
        throws IOException;
}

URLProcessorImpl.java



package com.example.cybrosys.sample;

import java.io.IOException;
import java.io.InputStream;


public class URLProcessorImpl extends URLProcessorBase {

 @Override
    protected void processURLData(InputStream input) throws IOException {
        int data = input.read();
        String str = "";
        while(data != -1){
            //System.out.println((char) data);
            str += (char) data;
            data = input.read();
        }
        System.out.println(str);
    }
}


1 comment:

  1. How To Make Money On Sports Betting
    Online sports betting is available for a whole host of US หารายได้เสริม and European wooricasinos.info sports betting markets. Some casinosites.one US states, kadangpintar like Louisiana and New Jersey, allow

    ReplyDelete