各位看官们大家好,上一回中咱们说的是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中服务大结局的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!
本文深入探讨Android服务的生命周期,详解Service与IntentService的区别及应用场景,通过完整代码示例,帮助读者掌握服务的创建、绑定与通信机制。
476

被折叠的 条评论
为什么被折叠?



