首页 > 代码库 > Activity和Service交互之bindService(回调更新UI)
Activity和Service交互之bindService(回调更新UI)
一.回调接口
public interface OnProgressListener { void onProgress(int progress); }
二.Service代码
public class MyService extends Service { private int progress = 0; private OnProgressListener onProgressListener; class DownLoadBinder extends Binder{ public MyService getService(){ return MyService.this; } } // 设置回调接口 public void setOnProgressListener(OnProgressListener onProgressListener){ this.onProgressListener = onProgressListener; } @Nullable @Override public IBinder onBind(Intent intent) { return new DownLoadBinder(); } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } // 模拟下载 public void startDownload(){ new Thread(new Runnable() { @Override public void run() { while (progress<100){ progress += 10; // 通知调用方 if( onProgressListener != null ){ onProgressListener.onProgress(progress); } try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } } }).start(); } // 获取progress public int getProgress(){ return progress; } @Override public void onDestroy() { super.onDestroy(); Log.e("Service", "onDestroy"); } }
三.Activity关键代码:
public class MainActivity extends Activity { private ProgressBar progressBar; private MyService myService; private int progress = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar)findViewById(R.id.progressBar); Intent intent = new Intent(this, MyService.class); // 标志位BIND_AUTO_CREATE是的服务中onCreate得到执行,onStartCommand不会执行 bindService(intent,conn, Context.BIND_AUTO_CREATE); } protected void myClick(View v){ if( v.getId() == R.id.btn ){ myService.startDownload(); } if( v.getId() == R.id.btn2 ){ unbindService(conn); } } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { unbindService(conn); super.onDestroy(); } ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { myService = ((MyService.DownLoadBinder)service).getService(); // 回调接口 myService.setOnProgressListener(new OnProgressListener() { @Override public void onProgress(int progress) { progressBar.setProgress(progress); } }); } @Override public void onServiceDisconnected(ComponentName name) { } }; }
Activity和Service交互之bindService(回调更新UI)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。