Android IntentService example
The following example is going to be of great help in understanding Android IntentService.
In the example I am going to use an activity and an IntentService. Let's name this activity as MainActivity and IntentService as FileService.
In the MainActivity startFileService method the putExtra parameter has key value pair, where "url" is the key and "http://www.textfiles.com/adventure/221baker.txt" is the value. This url is has a ".txt" file whose text is set to "TextView txtVw". And reading the ".txt" file from the url is done in the background using intent service.
Before going through the example, let us understand few concepts mentioned below:
IntentService : This handles asynchronous requests. Requests are received once the clients send requests through startService(Intent) call. Service is started as needed and each Intent is handled using a worker thread.
-onHandleIntent(Intent intent): This method is invoked on the worker thread with a request to process one intent at a time.
Intentfilter : This can match against actions.categories and data in an Intent.
- addAction(String action) : Matches new Intent action.
BroadcastReceiver: BroadcastReceiver responds to broadcast messages. Broadcast messages may be from other applications or from the system itself.
-onReveive(Context context, Intent intent) : This method is called when the broadcastReceiver is receiving an Intent broadcast.
-registerReceiver(BroadcastReceiver receiver, IntentFilter filter) : Register a broadcastReceiver to be run in the main activity thread.
Please set Internet permission in manifest as shown below:
activity_main:
MainActivity:
In the example I am going to use an activity and an IntentService. Let's name this activity as MainActivity and IntentService as FileService.
In the MainActivity startFileService method the putExtra parameter has key value pair, where "url" is the key and "http://www.textfiles.com/adventure/221baker.txt" is the value. This url is has a ".txt" file whose text is set to "TextView txtVw". And reading the ".txt" file from the url is done in the background using intent service.
Before going through the example, let us understand few concepts mentioned below:
IntentService : This handles asynchronous requests. Requests are received once the clients send requests through startService(Intent) call. Service is started as needed and each Intent is handled using a worker thread.
-onHandleIntent(Intent intent): This method is invoked on the worker thread with a request to process one intent at a time.
Intentfilter : This can match against actions.categories and data in an Intent.
- addAction(String action) : Matches new Intent action.
BroadcastReceiver: BroadcastReceiver responds to broadcast messages. Broadcast messages may be from other applications or from the system itself.
-onReveive(Context context, Intent intent) : This method is called when the broadcastReceiver is receiving an Intent broadcast.
-registerReceiver(BroadcastReceiver receiver, IntentFilter filter) : Register a broadcastReceiver to be run in the main activity thread.
Please set Internet permission in manifest as shown below:
<uses-permission android:name="android.permission.INTERNET"/>Firstly, let us prepare the xml for MainActivity and name it as activity_main.
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.pagingdemo.ajoshi.myservicepoc.MainActivity"> <TextView
android:id="@+id/textVw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" /> </RelativeLayout>
MainActivity:
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.util.Log; import android.widget.TextView; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class MainActivity extends AppCompatActivity { TextView txtVw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtVw = (TextView)findViewById(R.id.textVw); startFileService(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(FileService.TRANSACTION_TXT); registerReceiver(downloadReceiver,intentFilter); } void startFileService() { Intent intent = new Intent(this,FileService.class); intent.putExtra("url","http://www.textfiles.com/adventure/221baker.txt"); this.startService(intent); } private BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.e("FileService", "Service broadcasted"); showFileContent(); } }; void showFileContent() { StringBuilder sb; try { FileInputStream fis = this.openFileInput("mytxtFile"); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(isr); sb = new StringBuilder(); String line; while((line = bufferedReader.readLine())!= null) { sb.append(line).append("\n"); } txtVw.setText(sb.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
FileService:import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.util.Log; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class FileService extends IntentService { public static final String TRANSACTION_TXT = "com.pagingdemo.ajoshi.myservicepoc"; public FileService() { super("FileService"); } @Override protected void onHandleIntent(Intent intent) { Log.e("FileService","started"); String passedUrl = intent.getStringExtra("url"); downloadFile(passedUrl); Log.e("FileService","stopped"); Intent i = new Intent(TRANSACTION_TXT); FileService.this.sendBroadcast(i); // alert } public void downloadFile(String theUrl) { String filename = "mytxtFile"; try{ FileOutputStream outputStream = openFileOutput(filename, Context.MODE_PRIVATE); URL fileURL = new URL(theUrl); HttpURLConnection urlConnection = (HttpURLConnection)fileURL.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferlength = 0; while((bufferlength = inputStream.read(buffer))>0) { outputStream.write(buffer,0,bufferlength); } outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

Comments
Post a Comment