各位看官們大家好,上一回中咱們說的是Android中服務生命週期的例子,這一回咱們說的例子是服務的大結局。閒話休提,言歸正轉。讓我們一起Talk Android吧!
看官們,我們在前面章回中介紹了兩種服務,並且通過代碼演示瞭如何使用這兩種服務。與此同時還介紹了服務的運行狀態以及生命週期。本章回是對涉及服務所有章回的總結。還有一點就是給出完成的代碼,因爲有看官說,代碼放到步驟中容易理解,但是斷斷續續的代碼不方便運行,因此我們在本章回中展示所有的代碼;
首先說一下代碼的結構:Java文件一共三個:
- MainActivity:用來操作服務;
- ServiceA:是自定義service子類的文件;
- IntentServiceA:是自定義IntentService子類的文件;
下面是全部內容:
package com.example.talk8.blogapp06;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public String TAG = "ServiceA";
private Button mButtonStartService;
private Button mButtonStopService;
private Button mButtonBindService;
private Button mButtonUnBindService;
private Button mButtonStartIntentService;
private Button mButtonStopIntentService;
private Button mButtonBindIntentService;
private Button mButtonUnBindIntentService;
private Button mButtonStartIntentServiceByFooAction;
private ConnectionImpl mConnection;
private ServiceA.BinderSub mBinderSub;
private IntentServiceA.IntentServiceBinderSub mIntentServiceBinderSub;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "Activity onCreate: ThreadID: "+Thread.currentThread().getId());
Log.i(TAG, "Activity onCreate: ThreadID: "+Thread.currentThread().toString());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConnection = new ConnectionImpl();
//啓動,停止,綁定,解除綁定Service的Buttion
mButtonStartService = (Button)findViewById(R.id.id_start_service);
mButtonStopService = (Button)findViewById(R.id.id_stop_service);
mButtonBindService = (Button)findViewById(R.id.id_bind_service);
mButtonUnBindService = (Button)findViewById(R.id.id_unbind_service);
//啓動,停止,綁定,解除綁定IntentService的Buttion
mButtonStartIntentService = (Button)findViewById(R.id.id_start_intentservice);
mButtonStopIntentService = (Button)findViewById(R.id.id_stop_intentservice);
mButtonBindIntentService = (Button)findViewById(R.id.id_bind_intentservice);
mButtonUnBindIntentService = (Button)findViewById(R.id.id_unbind_intentservice);
//通過某種Action:Foo來啓動IntentService
mButtonStartIntentServiceByFooAction = (Button)findViewById(R.id.id_foo_intentservice);
mButtonStartIntentServiceByFooAction.setOnClickListener(v ->
IntentServiceA.startActionFoo(this,"Foo Action",null));
//給操作Service的Button添加事件監聽器
final Intent intent = new Intent(this,ServiceA.class);
mButtonStartService.setOnClickListener(v -> startService(intent));
mButtonStopService.setOnClickListener(v -> stopService(intent));
mButtonBindService.setOnClickListener(v -> bindService(intent,mConnection,this.BIND_AUTO_CREATE));
mButtonUnBindService.setOnClickListener(v -> unbindService(mConnection));
//給操作IntentService的Button添加事件監聽器
final Intent intentA = new Intent(this,IntentServiceA.class);
mButtonStartIntentService.setOnClickListener(v -> startService(intentA));
mButtonStopIntentService.setOnClickListener(v -> stopService(intentA));
mButtonBindIntentService.setOnClickListener(v -> bindService(intentA,mConnection,this.BIND_AUTO_CREATE));
mButtonUnBindIntentService.setOnClickListener(v -> unbindService(mConnection));
}
class ConnectionImpl implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(TAG, "onServiceConnected: ");
//使用服務提供的func方法來實現Activity和服務通信
if(service instanceof ServiceA.BinderSub) {
mBinderSub = (ServiceA.BinderSub) service;
mBinderSub.func();
}else if (service instanceof IntentServiceA.IntentServiceBinderSub) {
mIntentServiceBinderSub = (IntentServiceA.IntentServiceBinderSub) service;
mIntentServiceBinderSub.foo();
}else {
Log.i(TAG, "onServiceConnected: There is not Binder");
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBinderSub = null;
mIntentServiceBinderSub = null;
Log.i(TAG, "onServiceDisconnected: ");
}
}
}
package com.example.talk8.blogapp06;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class ServiceA extends Service {
private static final String TAG = "ServiceA";
private BinderSub mBinderSub = new BinderSub();
public ServiceA() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.i(TAG, "onBind: ");
if(mBinderSub != null)
return mBinderSub;
else
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ThreadID: "+Thread.currentThread().getId());
Log.i(TAG, "onCreate: ThreadName: "+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 boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy: ");
}
class BinderSub extends Binder {
public void func() {
Log.i(TAG, "func: do something of service.");
}
}
}
package com.example.talk8.blogapp06;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p>
* TODO: Customize class - update intent actions, extra parameters and static
* helper methods.
*/
public class IntentServiceA extends IntentService {
private static final String TAG = "IntentServiceA";
private IntentServiceBinderSub mBinder = new IntentServiceBinderSub();
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_FOO = "com.example.talk8.blogapp06.action.FOO";
private static final String ACTION_BAZ = "com.example.talk8.blogapp06.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "com.example.talk8.blogapp06.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.talk8.blogapp06.extra.PARAM2";
public IntentServiceA() {
super("IntentServiceA");
}
/**
* Starts this service to perform action Foo with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Log.i(TAG, "startActionFoo: ");
Intent intent = new Intent(context, IntentServiceA.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, IntentServiceA.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent: ThreadID: "+Thread.currentThread().getId());
Log.i(TAG, "onHandleIntent: ThreadName: "+Thread.currentThread().toString());
if (intent != null) {
final String action = intent.getAction();
if (ACTION_FOO.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFoo(param1, param2);
} else if (ACTION_BAZ.equals(action)) {
final String param1 = intent.getStringExtra(EXTRA_PARAM1);
final String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionBaz(param1, param2);
}
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void handleActionFoo(String param1, String param2) {
// TODO: Handle action Foo
if(param1 != null) {
Log.i(TAG, "handleActionFoo: param1: " + param1);
}else {
throw new UnsupportedOperationException("Not yet implemented");
}
}
/**
* Handle action Baz in the provided background thread with the provided
* parameters.
*/
private void handleActionBaz(String param1, String param2) {
// TODO: Handle action Baz
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate: ");
Log.i(TAG, "onCreate: ThreadID: "+Thread.currentThread().getId());
Log.i(TAG, "onCreate: ThreadName: "+Thread.currentThread().toString());
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind: ");
if (mBinder != null)
return mBinder;
else
return super.onBind(intent);
}
@Override
public int onStartCommand( Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy: ");
super.onDestroy();
}
class IntentServiceBinderSub extends Binder {
public void foo() {
Log.i(TAG, "foo of IntentServiceBinderSub: ");
}
}
}
各個Service使用的Binder子類是各自的內部類,位於各自的類文件中;ServiceConnection的實現類在MainActivity中,該文件中還定義各種Button以及爲它們設置監聽器;
xml佈局文件只有一個:activity_main。沒有使用複雜的佈局,裏面只有各種操作服務的Button.下面是全部內容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<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" />
<Button
android:id="@+id/id_bind_service"
android:text="Bind Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_unbind_service"
android:text="UnBind Service"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_start_intentservice"
android:text="Start IntentService"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_stop_intentservice"
android:text="Stop IntentService"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_bind_intentservice"
android:text="Bind IntentService"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_unbind_intentservice"
android:text="UnBind IntentService"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/id_foo_intentservice"
android:text="IntentService by foo Action"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
看官們,代碼雖然列出來了但是建議大家自己動手去實踐,特別是生命週期中的回調方法,大家可以結合程序運行時打印出來的log去理解。
各位看官,關於Android中服務大結局的例子咱們就介紹到這裏,欲知後面還有什麼例子,且聽下回分解!