BindService的繫結
阿新 • • 發佈:2018-11-06
public class MainActivity extends Activity {
private MBind mBind; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(MainActivity.this, MyService.class); ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public void onServiceConnected(ComponentName name, IBinder service) { // 繫結服務 mBind = (MyService.MBind) service; } }; // 開啟服務 bindService(intent, connection, Service.BIND_AUTO_CREATE); }
}
//Service裡面的程式碼
public class MyService extends Service {
private MBind mBind; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); mBind = new MBind(); } public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return mBind; } //建立自定義的類 繼承Binder public class MBind extends Binder { }
}