service简括五(IntentService,多线程,异步)

IntentService是service的子类

IntentService执行如下操作:

创建一个与应用程序主线程分开worker thread用来处理所有通过传递过来的Intent请求

创建一个work queue,一次只传递一个intent到onHandleIntent()方法中,从而不用担心多线程带来的问题

当处理完所有请求后自动停止服务,而不需要我们自己调用stopSelf()方法

默认实现了onBind()方法,返回值为null

默认实现了onStartCommand()方法,这个方法将会把我们的intent放到work queue中,然后在onHandleIntent()中执行。

public class MyServiceActivity extends Activity {
	protected static final String TAG = "MyServiceActivity";
	private Button btnStartNormalService;
	private Button btnStartIntentService;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartNormalService=(Button)findViewById(R.id.btnStartNormalService);
        btnStartIntentService=(Button)findViewById(R.id.btnStartIntentService);
        btnStartIntentService.setOnClickListener(listener);
        btnStartNormalService.setOnClickListener(listener);   
    }
	private OnClickListener listener=new OnClickListener()
	{		
		@Override
		public void onClick(View v)
		{
			Intent intent;
			switch (v.getId())
			{
			case R.id.btnStartNormalService: //自己写的多线程 service简括四中,有详细代码
				intent=new Intent(MyServiceActivity.this, mService.class);
				Log.i(TAG, "主线程ID:"+Thread.currentThread().getId());
				startService(intent);
				break;
			case R.id.btnStartIntentService://android中intentservice类的多线程
				intent=new Intent(MyServiceActivity.this, ExampleIntentService.class);
				Log.i(TAG, "主线程ID:"+Thread.currentThread().getId());
				startService(intent);
				break;
			default:
				break;
			}		
		}
	};
}
 public class ExampleIntentService extends IntentService {
	private static final String TAG = "ExampleIntentService";
	public ExampleIntentService() {
		super("ExampleIntentService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			Log.i(TAG,"Myservices线程Id"+Thread.currentThread().getId());
			Log.i(TAG,"正在下载中...");
			Thread.sleep(2000);

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

  当点击 btnStartIntentService时,会先把主线程ID等于多少打印出来,然后会在把Myservices线程Id打印出来,如果多次点击,会先把多次点击的主线程ID等于多少打印出来,然后把Myservices放到一个队列中,再一次一次的把队列中的Myservices线程Id等于多少打印出来,不知道解释清楚没有。。。直接上图

另外补充:

为什么要用多线程,从service简括一中,知道,activity和service是在同一个线程中,如果是一些耗时的操作时,在同一线程下非出现很多问题,同时客户端体验也不是很好,所以用多线程.

自己写多线程代码麻烦,所以就用IntentService 

如果不要求数据同步,异步执行,就可以用IntentService ,当然如果要是数据同步的话,就要继承service,并且重写onstartCommand()方法

猜你喜欢

转载自284772894.iteye.com/blog/1731281
今日推荐