各位看官們大家好,上一回中咱們說的是Android中service的例子,這一回咱們繼續說該例子。閒話休提,言歸正轉。讓我們一起Talk Android吧!
看官們,我們在上一章回中介紹瞭如何使用Service,不過沒有給出具體的代碼,這一回中我們將通過文字結合代碼的方式給大家演示如何使用Servie.詳細步驟如下:
- 1.創建一個工程,工程中包含一個空的Activity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
}
}
- 2.在Activity的佈局文件中添加兩個Buttion,用來啓動和停止服務;
<Button
android:id="@+id/id_start_service"
android:text="Start Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_stop_service"
android:text="Stop Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
protected void onCreate(Bundle savedInstanceState) {
mButtonStartService = (Button)findViewById(R.id.id_start_service);
mButtonStopService = (Button)findViewById(R.id.id_stop_service);
}
- 3.創建Service的子類ServiceA,並且重寫四個回調方法;
public class ServiceA extends Service {
private static final String TAG = "ServiceA";
public ServiceA() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ThreadID: "+Thread.currentThread().toString());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
}
- 4.在Activity的onCreate方法中給Button添加事件監聽器;
- 5.在Button的事件監聽器中調用的startService和stopService方法;
final Intent intent = new Intent(this,ServiceA.class);
mButtonStartService.setOnClickListener(v -> startService(intent));
mButtonStopService.setOnClickListener(v -> stopService(intent));
下面是程序的運行結果請大家參考:
//按下Start Service Button按鈕後打印出的log,從log中可以看到服務已經啓動
I/ServiceA: onCreate: ThreadID: Thread[main,5,main]
I/ServiceA: onStartCommand:
//按下Stop Service Button按鈕後打印出的log,從log中可以看到服務已經銷燬
I/ServiceA: onDestroy:
各位看官,關於Android中Service的例子咱們就介紹到這裏,欲知後面還有什麼例子,且聽下回分解!