intentservice的应用
intentservice是service的一个子类,这个类单独的开启了一个线程,利用handler的机制,把发送过来的intent放到消息列队中,一个接着一个的处理intent。
?
要使用这个类就要做到两条:
?1 ? public MyIntentService() {
? ? ? ? super("MyServicethread");
? ? }
2 ?protected void onHandleIntent(Intent intent) {
? ? ? ? Bundle bundle=intent .getExtras();
? ? ? ? int t1= bundle.getInt("t1");
? ? ? ? j=t1;
? ? ? ? switch (j) {
? ? ? ? ? ? case 11:
? ? ? ? ? ? ? ? i=j;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 22:
? ? ? ? ? ? ? ? i2=j;
? ? ? ? ? ? ? ? break;
?
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? ?Log.e(">>>>>>>>>>>>>>>>>>>>>>>>>111", ""+t1);
?
?
? ? }
例子:
1 <service android:name="MyIntentService"></service>在配置文件中加上;
2 MyIntentService 类
package com.hao.hello;
?
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
//使用IntentService,两点必须实现,一个是构造函数,另一个是实现onHandleIntent
public class MyIntentService extends IntentService {
? ? public static int i=0;
? ? public static int i2=0;
? ? int j;
//传入父类构造方法的字符串"MyServicethread"将作为工作线程的名字
? ? public MyIntentService() {
? ? ? ? super("MyServicethread");
? ? }
? ? @Override
? ? protected void onHandleIntent(Intent intent) {
? ? ? ? Bundle bundle=intent .getExtras();
? ? ? ? int t1= bundle.getInt("t1");
? ? ? ? j=t1;
? ? ? ? switch (j) {
? ? ? ? ? ? case 11:
? ? ? ? ? ? ? ? i=j;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 22:
? ? ? ? ? ? ? ? i2=j;
? ? ? ? ? ? ? ? break;
?
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? ?Log.e(">>>>>>>>>>>>>>>>>>>>>>>>>111", ""+t1);
?
?
? ? }
?
}
3 主activity的调用
?
package com.hao.hello;
?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
?
public class hello extends Activity {
? ? TextView textView,textView2;
? Handler handler=new Handler(){
? ? ? @Override
? ? public void handleMessage(Message msg) {
? ? ? ? ? switch (msg.what) {
? ? ? ? ? ? case 0:
? ? ? ? ? ? ? ? textView.setText("" + MyIntentService.i);
? ? ? ? ? ? ? ? handler.sendEmptyMessageDelayed(1, 50000);
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 1:
? ? ? ? ? ? ? ? textView2.setText("" + MyIntentService.i2);
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? break;
? ? ? ? }
?
? ? }
?
?
? };
?
? ? @Override
? ? public void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.main);
? ? ? ? Intent intent = new Intent(this, MyIntentService.class);
? ? ? ? intent.putExtra("t1", 11);
? ? ? ? startService(intent);
? ? ? ? Intent intent2 = new Intent(this, MyIntentService.class);
? ? ? ? intent.putExtra("t1", 22);
? ? ? ? startService(intent);
? ? ? ? textView = (TextView) findViewById(R.id.textView1);
? ? ? ? textView2=(TextView) findViewById(R.id.textView2);
? ? ? ? handler.sendEmptyMessageDelayed(0, 10000);
?
? ? }
}