Service启动,绑定与交互
1. Service的启动方式有startServcie和bindService两种。
startService时,会经历onCreate—onStartCommand—onDestroy生命周期,
bindService时,会经历onCreate—onBind—onUnbind—onDestroy生命周期。
2. Service与Activity之间交互时,可以通过bindService获取Service的连接的Binder,进而可以获取Service的引用,这样就可以与Service进行交互了。示例中,通过Service每秒更新TextView一次。
ICounterCallback接口
1 2 3 4 5 | package com.fxb.servicetest; public interface ICounterCallback { public void count( int val); } |
CountService类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | package com.fxb.servicetest; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class CountService extends Service{ private volatile boolean isRunning = true ; private CounterBinder counterBinder = new CounterBinder(); @Nullable @Override public IBinder onBind(Intent intent) { Log.i(MainActivity.TAG, "on bind!" ); return counterBinder; } public void startCounter( final int value, final ICounterCallback callback){ isRunning = true ; new AsyncTask<Integer, Integer, Void>() { @Override protected Void doInBackground(Integer... params) { int count = params[ 0 ]; while (isRunning){ try { Thread.sleep( 1000 ); count++; Log.i(MainActivity.TAG, Integer.toString(count)); publishProgress(count); } catch (InterruptedException e) { e.printStackTrace(); } } return null ; } @Override protected void onProgressUpdate(Integer... values) { super .onProgressUpdate(values); callback.count(values[ 0 ]); } }.execute( 0 ); } public void stopCounter(){ isRunning = false ; } @Override public void onCreate() { super .onCreate(); Log.i(MainActivity.TAG, "on create!" ); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(MainActivity.TAG, "on start command!" ); return super .onStartCommand(intent, flags, startId); } @Override public boolean onUnbind(Intent intent) { Log.i(MainActivity.TAG, "on unbind servcie!" ); return super .onUnbind(intent); } @Override public void onDestroy() { isRunning = false ; Log.i(MainActivity.TAG, "on destroy service" ); super .onDestroy(); } @Override public boolean stopService(Intent name) { Log.i(MainActivity.TAG, "on stop service!" ); return super .stopService(name); } public class CounterBinder extends Binder{ public CountService getService(){ return CountService. this ; } } } |
MainActivity类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | package com.fxb.servicetest; import android.app.Activity; 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 android.widget.TextView; public class MainActivity extends Activity implements View.OnClickListener, ICounterCallback{ public static final String TAG = "ServiceTest" ; private TextView tvShow; private Button btnStartServie, btnStopService; private Button btnBindService, btnUnbindService; private Button btnStartCounter, btnStopCounter; private CountService countService; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView(){ tvShow = (TextView)findViewById(R.id.tvShow); btnStartServie = (Button)findViewById(R.id.btnStartService); btnStopService = (Button)findViewById(R.id.btnStopService); btnBindService = (Button)findViewById(R.id.btnBindService); btnUnbindService = (Button)findViewById(R.id.btnUnbindService); btnStartCounter = (Button)findViewById(R.id.btnStartCount); btnStopCounter = (Button)findViewById(R.id.btnStopCount); btnStartServie.setOnClickListener( this ); btnStopService.setOnClickListener( this ); btnBindService.setOnClickListener( this ); btnUnbindService.setOnClickListener( this ); btnStartCounter.setOnClickListener( this ); btnStopCounter.setOnClickListener( this ); } private void startCountService(){ Intent intent = new Intent(MainActivity. this , CountService. class ); startService(intent); } private void stopCountService(){ Intent intent = new Intent(MainActivity. this , CountService. class ); stopService(intent); } private void myBindService(){ Intent intent = new Intent(MainActivity. this , CountService. class ); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); } private void myUnbindService(){ unbindService(serviceConnection); } @Override public void onClick(View v) { if (v == btnStartServie){ Log.i(TAG, "start click" ); startCountService(); } else if (v == btnStopService){ stopCountService(); } else if (v == btnBindService){ myBindService(); } else if (v == btnUnbindService){ myUnbindService(); } else if (v == btnStartCounter){ if (countService != null ){ countService.startCounter( 0 , this ); } } else if (v == btnStopCounter){ if (v == btnStopCounter){ countService.stopCounter(); } } } @Override public void count( int val) { tvShow.setText( "count:" +val); } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(MainActivity.TAG, "service connected!" ); CountService.CounterBinder binder = (CountService.CounterBinder)service; countService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName name) { Log.i(MainActivity.TAG, "service disconnected!" ); } }; } |
在bindService之后,点击startCount后,tvShow每隔1s更新一次,点击stopCount后停止更新。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!