.Net程序员玩转Android开发-Android IntentService服务
投稿于 被查看 19330 次 评论:22
.Net程序员玩转Android开发-Android IntentService服务
Intentservice服务也是安卓中的一个服务,它继承与service,但与servcie有所不同,它新开启一个线程来处理所有的请求, 不需要再UI等待处理,onStartCommand方法把所有请求发送到工作队列中,,然后再由工作队列发送到onHandlerIntent中进行处理
1.interservice默认情况下是新开启一个线程来处理任务, service默认是在ui线程执行
2. interservice会创建一个工作队列来处理接受到任务,只用当前任务处理完成,才能处理下一个任务,否则下一个任务一直处于等待状态.
3.所有的请求任务处理完成后,系统会自动停止服务,不需要手动停止stopselft
下面的例子展示intentservice不断接受外部传了的消息,并按顺序处理,首先在onStartCommand里面接受消息存入队列,然后在onHandleIntent进行处理
1.创建intentservice服务
package com.example.helloword; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Toast; public class ReceiveIntentService extends IntentService { String receivemsg; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { Toast.makeText(ReceiveIntentService.this, 接受消息: + receivemsg, Toast.LENGTH_LONG).show(); } }; public ReceiveIntentService() { super(1111); // TODO Auto-generated constructor stub } public ReceiveIntentService(String name) { super(name); // TODO Auto-generated constructor stub } @Override public int onStartCommand(Intent intent, int flags, int startId) { Bundle bundle = intent.getExtras(); receivemsg= bundle.getString(para); return super.onStartCommand(intent, flags, startId); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.sendEmptyMessage(0); } }
2.通过activity不断向intentservice发送消息
布局文件
后台IntentActivity
package com.example.helloword; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class IntentActivity extends Activity { private Button btnpost;//启动服务 private EditText etmsg; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.intentlayout); btnpost=(Button)findViewById(R.id.btnpostmsg); etmsg=(EditText)findViewById(R.id.etpostmsg); btnpost.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub intent = new Intent(com.example.helloword.ReceiveIntentService); Bundle bundle = new Bundle(); bundle.putString(para,etmsg.getText().toString()); intent.putExtras(bundle); startService(intent); } }); } }
??
用户评论