由於多數啓動服務沒必要同時處理多個請求(在多線程情景下會很危險),因此使用IntentService類實現服務是很好的選擇。本經驗將經過繼承IntentService輸出當前時間教你們如何使用IntentService。java
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.basillee.asus.demo.MainActivity5"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="當前時間" android:id="@+id/button_current_time" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
而後咱們在編寫一個CurrentTimeService類,繼承IntentServiceandroid
package com.basillee.asus.demo; import android.app.IntentService; import android.content.Intent; import android.text.format.Time; import android.util.Log; public class CurrentTimeService extends IntentService { public CurrentTimeService(){ super("CurrentTimeService"); } @Override protected void onHandleIntent(Intent intent) { Time time=new Time(); time.setToNow(); String currentTime=time.format("%Y-%m-%d %H:%M:%S"); Log.i("CurrentTimeService",currentTime); } }
而後咱們在Oncreate方法裏面編寫以下代碼爲button增長監聽事件多線程
package com.basillee.asus.demo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity5 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_activity5); Button button= (Button) findViewById(R.id.button_current_time); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(new Intent(MainActivity5.this, CurrentTimeService.class)); } }); } }
更多細節請看: http://jingyan.baidu.com/season/48891app