Intent Service Example Code
The
IntentService
class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService
isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask
An IntentService
has a few limitations:
- It can't interact directly with your user interface. To put its results in the UI, you have to send them to an
Activity
. - Work requests run sequentially. If an operation is running in an
IntentService
, and you send it another request, the request waits until the first operation is finished. - An operation running on an
IntentService
can't be interrupted.
However, in most cases an
IntentService
is the preferred way to simple background operations.
This lesson shows you how to create your own subclass of
IntentService
. The lesson also shows you how to create the required callback method onHandleIntent()
. Finally, the lesson describes shows you how to define the IntentService
in your manifest file.Extending the IntentService class
Because most started services don't need to handle multiple requests simultaneously (which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using the
IntentService
class.
The
IntentService
does the following:- Creates a default worker thread that executes all intents delivered to
onStartCommand()
separate from your application's main thread. - Creates a work queue that passes one intent at a time to your
onHandleIntent()
implementation, so you never have to worry about multi-threading. - Stops the service after all start requests have been handled, so you never have to call
stopSelf()
. - Provides default implementation of
onBind()
that returns null. - Provides a default implementation of
onStartCommand()
that sends the intent to the work queue and then to youronHandleIntent()
implementation.
All this adds up to the fact that all you need to do is implement
onHandleIntent()
to do the work provided by the client. (Though, you also need to provide a small constructor for the service.)
Intent Service Example Code
This code start intent service to download for URL.
MainActivity.java Code
package
com.example.androidintentservice;
import
android.os.Bundle;
import
android.app.Activity;
import
android.content.BroadcastReceiver;
import
android.content.Context;
import
android.content.Intent;
import
android.content.IntentFilter;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.ProgressBar;
import
android.widget.TextView;
public class
MainActivity extends Activity {
TextView textResult;
ProgressBar progressBar;
private
MyBroadcastReceiver myBroadcastReceiver;
private
MyBroadcastReceiver_Update myBroadcastReceiver_Update;
@Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult =
(TextView)findViewById(R.id.result);
progressBar =
(ProgressBar)findViewById(R.id.progressbar);
myBroadcastReceiver = new
MyBroadcastReceiver();
myBroadcastReceiver_Update = new
MyBroadcastReceiver_Update();
//register BroadcastReceiver
IntentFilter intentFilter = new
IntentFilter(MyIntentService.ACTION_MyIntentService);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver,
intentFilter);
IntentFilter intentFilter_update = new
IntentFilter(MyIntentService.ACTION_MyUpdate);
intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver_Update,
intentFilter_update);
// btnDownload
Button startBtn =
(Button)findViewById(R.id.buttonDownload);
startBtn.setOnClickListener(new
OnClickListener(){
public void
onClick(View v) {
//prepare
MyParcelable passing to intentMyIntentService
String msgToIntentService = "Android
Example : Intent Service Start";
//Start
MyIntentService
Intent
intentMyIntentService = new Intent(MainActivity.this,
MyIntentService.class);
intentMyIntentService.putExtra(MyIntentService.EXTRA_KEY_IN,
msgToIntentService);
intentMyIntentService.putExtra(MyIntentService.FILENAME, "SourcecodeBeginningAndroid.zip");
intentMyIntentService.putExtra(MyIntentService.URL,"http://www.digital2u.net/media/Android/SourcecodeBeginningAndroid.zip");
startService(intentMyIntentService);
}
});
}//onCreate
@Override
protected void onDestroy()
{
super.onDestroy();
//un-register
BroadcastReceiver
unregisterReceiver(myBroadcastReceiver);
unregisterReceiver(myBroadcastReceiver_Update);
}
public class
MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void
onReceive(Context context, Intent intent) {
String result =
intent.getStringExtra(MyIntentService.EXTRA_KEY_OUT);
textResult.setText(result);
}
}
public class
MyBroadcastReceiver_Update extends BroadcastReceiver {
@Override
public void
onReceive(Context context, Intent intent) {
int update =
intent.getIntExtra(MyIntentService.EXTRA_KEY_UPDATE, 0);
progressBar.setProgress((int) update);
}
}
}
MyIntentService.java Code
package
com.example.androidintentservice;
import
java.io.File;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.net.URL;
import
android.app.IntentService;
import
android.content.Intent;
import
android.os.Environment;
public class
MyIntentService extends IntentService {
public static final String ACTION_MyIntentService = "com.example.androidintentservice.RESPONSE";
public static final String ACTION_MyUpdate = "com.example.androidintentservice.UPDATE";
public static final String EXTRA_KEY_IN = "EXTRA_IN";
public static final String EXTRA_KEY_OUT = "EXTRA_OUT";
public static final String EXTRA_KEY_UPDATE = "EXTRA_UPDATE";
String msgFromActivity;
String extraOut;
public static final String URL = "url";
public static final String FILENAME = "filename";
public static final String FILEPATH = "/sdcard/";
public static final String RESULT = "result";
public static final String NOTIFICATION = "android.example.intentsevice";
public
MyIntentService() {
super("com.example.androidintentservice.MyIntentService");
}
@Override
protected void
onHandleIntent(Intent intent) {
msgFromActivity =
intent.getStringExtra(EXTRA_KEY_IN);
extraOut = msgFromActivity;
Intent intentResponse = new Intent();
intentResponse.setAction(ACTION_MyIntentService);
intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
intentResponse.putExtra(EXTRA_KEY_OUT, extraOut);
sendBroadcast(intentResponse);
String urlPath =
intent.getStringExtra(URL);
String fileName =
intent.getStringExtra(FILENAME);
// String urlPath =
"http://www.digital2u.net/media/Android/SourcecodeBeginningAndroid.zip";
// String fileName =
"SourcecodeBeginningAndroid.zip";
File output = new
File(Environment.getExternalStorageDirectory(),fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
long total = 0;
int progress =
0;
try {
URL url = new
URL(urlPath);
stream =
url.openConnection().getInputStream();
InputStreamReader reader = new
InputStreamReader(stream);
fos = new
FileOutputStream(output.getPath());
int next = -1;
while ((next =
reader.read()) != -1) {
fos.write(next);
progress++;
total += next;
Intent intentUpdate = new Intent();
intentUpdate.setAction(ACTION_MyUpdate);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(EXTRA_KEY_UPDATE, progress);
sendBroadcast(intentUpdate);
intentResponse.setAction(ACTION_MyIntentService);
intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
intentResponse.putExtra(EXTRA_KEY_OUT, "Data
Received : "+total +" Bytes");
sendBroadcast(intentResponse);
}
} catch (Exception
e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch
(IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch
(IOException e) {
e.printStackTrace();
}
}
}
//return result
//intentResponse = new Intent();
intentResponse.setAction(ACTION_MyIntentService);
intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
intentResponse.putExtra(EXTRA_KEY_OUT, "Download
Done ! "+total +"Bytes");
sendBroadcast(intentResponse);
}
}
AndroidManifest.xml Code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidintentservice"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"
/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
>
<activity
android:name="com.example.androidintentservice.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="com.example.androidintentservice.MyIntentService"></service>
</application>
</manifest>
สอนเขียน Android สอนเขียนโปรแกรม Android แบบ Online
รับสอนเขียนโปรแกรม Android App สอนแบบ online สอนสด ตัวต่อตัว หรือ เป็นกลุ่ม ได้ทั่วประเทศ กำหนดเวลาเรียนได้
การเรียน Android App แบบ online สามารถกำหนดเวลาเรียน เองได้ ตามแต่ตกลงกัน
( รับสอน นอกสถานที่ แบบเป็น กลุ่ม ทั่วประเทศ )
แต่ละ Course ขึ้นอยู่กับพื้นฐานที่มี นะครับ
Course
1.JAVA Programming สำหรับผู้ที่ยังไม่มีพื้นฐานทางด้าน การเขียนโปรแกรม JAVA
เรียน 3-4 ครั้ง ครั้งละ 2 ชั่วโมง
2.Beginning Android Development เริ่มต้นการพัฒนาด้วย Android ( ต้องมีพื้นฐาน JAVA แล้ว )
เรียน 5-6 ครั้ง ครั้งละ 2 ชั่วโมง
เรียนจบคอร์สนี้ ก็สามารถทำ Application ได้แล้ว
3.Android Application สอนตามความต้องการในการเขียนโปรแกรม ใช้งานจริง เช่น โปรแกรมใช้งานด้านต่างๆ
ระยะเวลา และ ค่าเรียน ตามแต่ความยากง่ายของโปรแกรม ซึ่งอาจจะรวมสอน JAVA Programming ด้วยสำหรับผู้เริ่มต้นเลย
ดังนั้น ราคาสอน จะขึ้นอยู่กับ สเปคงาน
โปรแกรมที่ใช้ทำการเรียน Team Viewer Version ล่าสุด Version 8
Meeting ID จะแจ้งให้ก่อนเรียน ผ่านทาง email sms Line หรือ อื่นๆ ตามสะดวก
ใช้ Tab Meeting ใส่ Meeting ID และใส่ชื่อ
แล้ว Join Meeting
ติดต่อ amphancm@gmail.com
ติดต่อ amphancm@gmail.com