安卓基础之《(28)—Service组件》

张开发
2026/6/1 6:16:20 15 分钟阅读
安卓基础之《(28)—Service组件》
一、Service概述1、Service是什么Service是一个应用组件它用来在后台完成一个时间跨度比较大的工作且没有关联任何界面2、应用退出Service还在运行3、一个Service可以完成访问网络、播放音乐、文件IO操作、大数据量的数据库操作4、Service的特点1Service在后台运行不用与用户进行交互2即使应用退出服务也不会停止3启动应用会创建一个进程应用退出但是进程没死4在默认情况下Service运行在应用程序进程的主线程UI线程中如果需要在Service中处理一些网络连接等耗时的操作那么应该将这些任务放在子线程中处理避免阻塞用户界面二、Service的分类1、Local Service本地服务Service对象与Service的启动者在同个进程中运行两者的通信是进程内通信2、Remote Service远程服务Service对象与Service的启动者不在同一个进程中运行这时存在一个进程间通信的问题android专门为此设计了AIDL来实现进程间通信三、本地Service1、声明Service在清单文件AndroidManifest.xml中静态声明‌2、启动与停止Service方式一一般启动startService(Intent intent)stopService(Intent intent)方式二绑定启动bindService(Intent intent, ServiceConnection connection)unbindService(ServiceConnection connection)3、只有当onBind()、onUnBind()方法执行了才会执行ServiceConnection里的方法当服务连接时如果绑定的服务onBind()没有返回值则不执行onServiceConnected()方法4、例子LocalServiceActivity.javapackage com.example.chapter10; import androidx.appcompat.app.AppCompatActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.widget.Button; import com.example.chapter10.service.LocalService; public class LocalServiceActivity extends AppCompatActivity implements View.OnClickListener { private Button btn_start; private Button btn_stop; private Button btn_bind; private Button btn_unbind; private ServiceConnection conn; Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_local_service); findViewById(R.id.btn_start).setOnClickListener(this); findViewById(R.id.btn_stop).setOnClickListener(this); findViewById(R.id.btn_bind).setOnClickListener(this); findViewById(R.id.btn_unbind).setOnClickListener(this); } Override public void onClick(View view) { if (view.getId() R.id.btn_start) { startMyService(view); } else if (view.getId() R.id.btn_stop) { stopMyService(view); } else if (view.getId() R.id.btn_bind) { bindMyService(view); } else if (view.getId() R.id.btn_unbind) { unbindMyService(view); } } // 启动服务 public void startMyService(View v) { // 用显式意图传入要启动的服务类 Intent intent new Intent(this, LocalService.class); startService(intent); Log.d(sam, startMyService 启动服务); } // 停止服务 public void stopMyService(View v) { Intent intent new Intent(this, LocalService.class); stopService(intent); Log.d(sam, stopMyService 停止服务); } // 绑定服务 public void bindMyService(View v) { Intent intent new Intent(this, LocalService.class); if (conn null) { // 创建连接对象 conn new ServiceConnection() { Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { // 当activity和service连接上时调用这个方法 Log.d(sam, onServiceConnected 服务连接); } Override public void onServiceDisconnected(ComponentName componentName) { Log.d(sam, onServiceDisconnected 服务断开连接); } }; // 绑定service bindService(intent, conn, Context.BIND_AUTO_CREATE); } else { Log.d(sam, 已经绑定); } } // 解绑服务 public void unbindMyService(View v) { if (conn ! null) { // 解绑service unbindService(conn); conn null; } else { Log.d(sam, 还没有绑定); } } }布局文件activity_local_service.xml?xml version1.0 encodingutf-8? LinearLayout xmlns:androidhttp://schemas.android.com/apk/res/android xmlns:apphttp://schemas.android.com/apk/res-auto xmlns:toolshttp://schemas.android.com/tools android:layout_widthmatch_parent android:layout_heightmatch_parent android:orientationvertical tools:context.LocalServiceActivity TextView android:layout_widthmatch_parent android:layout_heightwrap_content android:text测试启动本地服务 android:textSize17sp android:gravitycenter/ Button android:idid/btn_start android:layout_widthmatch_parent android:layout_heightwrap_content android:text启动服务/ Button android:idid/btn_stop android:layout_widthmatch_parent android:layout_heightwrap_content android:text停止服务/ TextView android:layout_widthmatch_parent android:layout_heightwrap_content android:text测试绑定本地服务 android:textSize17sp android:gravitycenter/ Button android:idid/btn_bind android:layout_widthmatch_parent android:layout_heightwrap_content android:text绑定服务/ Button android:idid/btn_unbind android:layout_widthmatch_parent android:layout_heightwrap_content android:text解绑服务/ /LinearLayout清单文件?xml version1.0 encodingutf-8? manifest xmlns:androidhttp://schemas.android.com/apk/res/android application android:allowBackuptrue android:iconmipmap/ic_launcher android:labelstring/app_name android:roundIconmipmap/ic_launcher_round android:supportsRtltrue android:themestyle/Theme.MyApplication activity android:name.LocalServiceActivity android:exportedtrue intent-filter action android:nameandroid.intent.action.MAIN / category android:nameandroid.intent.category.LAUNCHER / /intent-filter /activity service android:name.service.LocalService android:enabledtrue android:exportedfalse / /application /manifest自定义本地服务LocalService.javapackage com.example.chapter10.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; import androidx.annotation.Nullable; /** * 自定义本地服务 */ public class LocalService extends Service { public LocalService() { Log.d(sam, LocalService()); } Nullable Override public IBinder onBind(Intent intent) { Log.d(sam, LocalService onBind()); // 返回自定义Binder实例 return new BasisBind(); } Override public boolean onUnbind(Intent intent) { Log.d(sam, LocalService onUnbind()); return super.onUnbind(intent); } Override public void onCreate() { super.onCreate(); Log.d(sam, LocalService onCreate()); } Override public void onDestroy() { super.onDestroy(); Log.d(sam, LocalService onDestroy()); } public class BasisBind extends Binder { } }5、日志绑定/解绑2026-04-13 17:17:10.517 13398-13398 sam com.example.chapter10 D LocalService() 2026-04-13 17:17:10.523 13398-13398 sam com.example.chapter10 D LocalService onCreate() 2026-04-13 17:17:10.526 13398-13398 sam com.example.chapter10 D LocalService onBind() 2026-04-13 17:17:10.536 13398-13398 sam com.example.chapter10 D onServiceConnected 服务连接 2026-04-13 17:17:14.453 13398-13398 sam com.example.chapter10 D LocalService onUnbind() 2026-04-13 17:17:14.454 13398-13398 sam com.example.chapter10 D LocalService onDestroy()onServiceDisconnected仅在服务因异常情况被系统终止时触发‌而不是在正常解绑服务时调用

更多文章