一、总体工程图
二、activity_intent_service.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:text="startIntentService"
android:id="@+id/buttonIntentService"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Button>
</LinearLayout>
三、AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jltxgcy.intentservicedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".IntentServiceActivity"
android:label="@string/title_activity_intent_service" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".HelloIntentService">
</service>
</application>
</manifest>
四、IntentServiceActivity.java
package com.jltxgcy.intentservicedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class IntentServiceActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent_service);
findViewById(R.id.buttonIntentService).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(IntentServiceActivity.this, HelloIntentService.class);
startService(intent);
}
});
}
}
五、HelloIntentService.java
package com.jltxgcy.intentservicedemo;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class HelloIntentService extends IntentService {
public static final String TAG="jltxgcy";
public HelloIntentService() {
super("HelloIntentService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Log.d(TAG, "onHandleIntent"+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}
六、详解
大家看到了实现的功能和上篇StartService的功能一样,参考StartService链接http://blog.csdn.net/jltxgcy/article/details/10295963。
Logcat显示结果如下:
说明了onHandleIntent在子线程中,而且程序结束后会自动调用stopSelf,从而执行onDestory方法结束Service。
代码地址:https://github.com/jltxgcy/Demo