extends IntentService to create your own Intent : Intent « Core Class « Android






extends IntentService to create your own Intent

    
package app.test;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

class MyIntentService extends IntentService {

  public MyIntentService() {
    super("MyIntentServiceName");
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    try {
      int result = DownloadFile(new URL("http://a.com/b.pdf"));
      Log.d("IntentService", "Downloaded " + result + " bytes");
      Intent broadcastIntent = new Intent();
      broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
      getBaseContext().sendBroadcast(broadcastIntent);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }

  private int DownloadFile(URL url) {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }
}

class MyService extends Service {
  int counter = 0;
  public URL[] urls;

  static final int UPDATE_INTERVAL = 1000;
  private Timer timer = new Timer();

  private final IBinder binder = new MyBinder();

  public class MyBinder extends Binder {
    MyService getService() {
      return MyService.this;
    }
  }

  @Override
  public IBinder onBind(Intent arg0) {
    return binder;
  }

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

    try {
      int result = DownloadFile(new URL("http://amazon.com"));
      Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes",
          Toast.LENGTH_LONG).show();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    try {
      new DoBackgroundTask().execute(new URL("http://a.com/a.pdf"),
          new URL("http://b.com/b.pdf"),
          new URL("http://c.com/c.pdf"),
          new URL("http://d.net/d.pdf"));

    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    doSomethingRepeatedly();

    Object[] objUrls = (Object[]) intent.getExtras().get("URLs");
    URL[] urls = new URL[objUrls.length];
    for (int i = 0; i < objUrls.length - 1; i++) {
      urls[i] = (URL) objUrls[i];
    }
    new DoBackgroundTask().execute(urls);

    return START_STICKY;
  }

  private void doSomethingRepeatedly() {
    timer.scheduleAtFixedRate(new TimerTask() {
      public void run() {
        Log.d("MyService", String.valueOf(++counter));
        try {
          Thread.sleep(4000);
          Log.d("MyService", counter + " Finished");

        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }, 0, UPDATE_INTERVAL);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (timer != null) {
      timer.cancel();
    }
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  }

  private int DownloadFile(URL url) {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }

  private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {
      int count = urls.length;
      long totalBytesDownloaded = 0;
      for (int i = 0; i < count; i++) {
        totalBytesDownloaded += DownloadFile(urls[i]);
        publishProgress((int) (((i + 1) / (float) count) * 100));
      }
      return totalBytesDownloaded;
    }

    protected void onProgressUpdate(Integer... progress) {
      Log.d("Downloading files", String.valueOf(progress[0])
          + "% downloaded");
      Toast.makeText(getBaseContext(),
          String.valueOf(progress[0]) + "% downloaded",
          Toast.LENGTH_LONG).show();
    }

    protected void onPostExecute(Long result) {
      Toast.makeText(getBaseContext(), "Downloaded " + result + " bytes",
          Toast.LENGTH_LONG).show();
      stopSelf();
    }
  }
}

public class Test extends Activity {
  IntentFilter intentFilter;
  private MyService serviceBinder;
  Intent i;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    intentFilter = new IntentFilter();
    intentFilter.addAction("FILE_DOWNLOADED_ACTION");
    registerReceiver(intentReceiver, intentFilter);

    Button btnStart = (Button) findViewById(R.id.btnStartService);
    btnStart.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {

        Intent intent = new Intent(getBaseContext(), MyService.class);
        try {
          URL[] urls = new URL[] { new URL("http://a.com/a.pdf"),
              new URL("http://b.com/b.pdf"),
              new URL("http://c.com/c.pdf"),
              new URL("http://d.com/d.pdf") };
          intent.putExtra("URLs", urls);

        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
        startService(intent);

        startService(new Intent(getBaseContext(), MyService.class));
        startService(new Intent("app.test.MyService"));
        startService(new Intent(getBaseContext(), MyIntentService.class));

        i = new Intent(Test.this, MyService.class);
        bindService(i, connection, Context.BIND_AUTO_CREATE);
      }
    });

    Button btnStop = (Button) findViewById(R.id.btnStopService);
    btnStop.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        stopService(new Intent(getBaseContext(), MyService.class));
      }
    });
  }

  private ServiceConnection connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
      serviceBinder = ((MyService.MyBinder) service).getService();
      try {
        URL[] urls = new URL[] { new URL("http://a.com/a.pdf"),
            new URL("http://b.com/b.pdf"),
            new URL("http://c.com/c.pdf"),
            new URL("http://d.net/d.pdf") };
        serviceBinder.urls = urls;
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
      startService(i);
    }

    public void onServiceDisconnected(ComponentName className) {
      serviceBinder = null;
    }
  };
  private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      Toast.makeText(getBaseContext(), "File downloaded!",
          Toast.LENGTH_LONG).show();
    }
  };
}

//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"
    >
<Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="Start Service" />
        
<Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="Stop Service" />
        
</LinearLayout>

   
    
    
    
  








Related examples in the same category

1.Using Intent to open other Activity
2.Create Intent to open a Uri
3.extends IntentService
4.Phone Intent
5.Map Intent
6.Market Intent
7.Load Activity with Intent
8.Using Intent to make another phone call
9.Adding data bundle to Intent
10.Using Intent to show other Activities
11.Start Intent with Utility class
12.Load library Activity with Intent
13.Capture Image with Intent
14.Intent.ACTION_MEDIA_MOUNTED
15.Using Intent to record audio
16.Video Player Intent
17.Video Capture Intent
18.Implementing an application service that will run in response to an alarm, allowing us to move long duration work out of an intent receiver.
19.Example of various Intent flags to modify the activity stack.
20.Sample code that invokes the speech recognition intent API.
21.extends IntentService to upload a file
22.factory class for generating various intents
23.Open Web Page Intent
24.Is Intent Available
25.start MMS Intent
26.Access the Internet
27.Pdf viewer
28.Rotation One Demo
29.Media activity