Android binding services (easy way)

Keywords: Android xml Java

An easy way for Android to bind services
Here are the services:
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
Binding services provide a client server interface to allow components to interact, send requests, get results, and even use interprocess communication (IPC) to complete these operations across processes.
When the project calls bindService() of Context to obtain a service persistent connection, it will call back the onBind() method in the service. Similarly, if the service has not been created before, the onCreate() method will execute before the onBind () method. After that, the caller can get an instance of the IBinder object returned by the onBind () method, so that the word can communicate with the service. As long as the connection between the caller and the service is not broken, the service remains running.
I believe the Android example is clearer.
First create an Android project.
Write the following code in xml:






<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Implement binding service"
        android:gravity="center"
        android:textSize="20sp"
         />
    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Binding services"
        />
    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind"
        />
    <Button
        android:id="@+id/random"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get random number"
        />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="22sp"
        android:gravity="center"
        />


</LinearLayout>

Create three buttons and a text box to get the number.
Next, create a service. I won't explain how to create a service in detail here. In the previous article, I introduced how to create a service using Android customization.
Link: https://blog.csdn.net/jzdcuccess/article/details/105604156 . this is the last project I created.
Create a service named bindservice with the following code:


public class BindService extends Service {
    int num=0;
    public int getRandom(){
        num=new Random().nextInt(100);
        return num;
    }

    public class MyBinder extends Binder{
        public int getRandom(){

            return BindService.this.getRandom();


        }
    }
    @Override
    public IBinder onBind(Intent intent) {

        return new MyBinder();
    }
}

Create a getRandom() class to get random numbers.
onBind: the onBind method in Service is an abstract method, so the Service class itself is an abstract class, that is to say, the onBind method must be overridden, that is, it cannot be used. When using Service through startService, when we rewrite the onBind method, we only need to set its return value to null. The onBind method is mainly used to call Service for the bindService method.
The internal class Binder (MyBinder) is established to bind the client and the server to return the Binder object in the Service's onBind method.
In the onBinder object, we return the IBinder object (MyBinder we wrote) which is used to define the program interface used by the client to interact with the service, that is, through the object, we can realize the communication with the bound service. The IBinder object is usually implemented by inheriting binder's implementation class. (our MyBinder is implemented by inheriting binder above). Binder can configure different service services.
Then write the following code in java:
Here are some inline snippets.




public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private BindService bindService;
    private BindService.MyBinder myBinder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bind_service=(Button)findViewById(R.id.bind_service);
        Button unbind_service=(Button)findViewById(R.id.unbind_service);
        Button button3=(Button)findViewById(R.id.random);
        bind_service.setOnClickListener(this);
        unbind_service.setOnClickListener(this);
        button3.setOnClickListener(this);

    }
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder=(BindService.MyBinder) service; //Cast type
            Toast.makeText(MainActivity.this,"Services bound",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bind_service:
                Intent intent=new Intent(MainActivity.this,BindService.class);
                bindService(intent,connection, Context.BIND_AUTO_CREATE);
                break;
            case R.id.unbind_service:
               unbindService(connection);
               // Intent intent1=new Intent(MainActivity.this,BindService.class);
                //stopService(intent1);
                Toast.makeText(MainActivity.this,"Unbind",Toast.LENGTH_SHORT).show();
                break;
            case R.id.random:
                int num=myBinder.getRandom();
                TextView textView=(TextView)findViewById(R.id.textView1);

                textView.setText("The random number obtained is:"+num);
                break;
                default:
                    break;
        }

    }
}

This simply creates a case of binding services:

This has been accomplished. If there is any mistake, please correct it.
At last, I add some poems that I feel good about. (don't shout. It's just a hobby)
In the future, if you are so ambitious, dare to laugh that Huang Chao is not a husband.



Posted by tcsnguy08 on Wed, 22 Apr 2020 22:06:47 -0700