Service与Activity通信

Service与Activity通信

1、实现步骤:

  • 添加一个继承Binder的内部类,并添加相应的逻辑方法

  • 重写Service的onBind方法,返回我们刚刚定义的那个内部类实例

  • 重写ServiceConnection,onServiceConnected时调用逻辑方法 绑定服务

2、实例:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
   private MyConn mConn;
   private MyService.IBinder mBinder;
   private Button mButton;
   private Button mButton2;
   private boolean isBind = false;
   private Intent mIntent;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main_layout);

       mIntent = new Intent(this,MyService.class);
       mConn = new MyConn();
       bindService(mIntent,mConn,BIND_AUTO_CREATE);
       isBind = true;

       mButton = findViewById(R.id.button);
       mButton.setOnClickListener(this);

       mButton2 = findViewById(R.id.button2);
       mButton2.setOnClickListener(this);
  }

   @Override
   protected void onDestroy() {
       if (isBind){
           unbindService(mConn);
      }
       super.onDestroy();
  }

   @Override
   public void onClick(View v) {
       int i = v.getId();
       switch (i){
           case R.id.button:
               mBinder.callMyService(2);
               break;
           case R.id.button2:
               if (isBind){
                   unbindService(mConn);
                   isBind = false;
              }
               break;
      }

  }

   public class MyConn implements ServiceConnection{

       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
           mBinder = (MyService.IBinder) service;
      }

       @Override
       public void onServiceDisconnected(ComponentName name) {

      }
  }
}

MyService.java

public class MyService extends Service {
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
       return new IBinder();
  }
   public void testFun(int num){
       if (num==1){
           Toast.makeText(getApplicationContext(),"this is one!",Toast.LENGTH_SHORT).show();
      }
       if (num==2){
           Toast.makeText(getApplicationContext(),"this is two!",Toast.LENGTH_SHORT).show();
      }

  }

   //这里的IBinder相当于一个不赚差价的中间商
   public class IBinder extends Binder{

       public void callMyService(int num){
           testFun(num);
      }
  }
}

注意:一定要在清单文件中添加

<service android:name=".MyService"/>

 

原文地址:https://www.cnblogs.com/littleboy123/p/12978624.html