Android SDK package, provide external interfaces

Projects need to make a connection to the server portion and generates a service module jar. Other products by this package can be connected quickly develop server applications. Make a service advantages are:

1. In the background, you can always stay connected to the server

2. Services can only provide external interfaces, the specific function is implemented in-house services

3. Increasing the coupling of the project code

Open the sdk I use several third-party jar package look:

2968974-f64527fbc8ce236b
2968974-e0721d4d2d9b7d0e

This is the contents of a jar packet voice recognition sdk micro-letter

2968974-0ae956af618ad6b9

We develop a general sdk course, is the definition of remote service, which is initiated by way of bingservice start the service.

At the same time, the way of communication applications and services have Messenger and aidl, look at the difference between the specific article of it.

We are here to develop a sdk, and therefore chose to use aidl, of course, if your sdk does not contain any service, there is no such thing as a child.

Now to describe an example and create a service call process. Examples of the function is to set a numeric value to the service, and then read out from the service inside. The main interface for placing two or more buttons for triggering two actions, the result of the call is displayed in logcat.

First create a project, and then create a package in the project src Next, place the code for the service as well as a package for placing aidl file. In turn placed inside the bag and aidl service class file. After you have created, as follows.

Which CloudServiceInterface.aidl document reads as follows:

packagecom.rayleigh.aidl;


interfaceCloudServiceInterface {

   void setInfo(intperson);

   int  getInfo();

}

CloudService.java file reads as follows:

packagecom.rayleigh.cloud;


importcom.rayleigh.aidl.CloudServiceInterface;


import android.app.Service;

importandroid.content.Intent;

importandroid.os.IBinder;

importandroid.util.Log;


publicclass CloudService extends Service {


       private int testdata = 0;

    public CloudService() {

    }


    private static final StringTAG="Test";


    @Override

    public void onCreate()

    {

        Log.i(TAG, "ServiceonCreate--->");

        //TODO:register broadcast

        //// TODO: 2016/12/18  or start do something

        super.onCreate();

    }


    @Override

    public int onStartCommand(Intent intent,int flags, int startId) {

       // return super.onStartCommand(intent,flags, startId);

        return START_STICKY;

    }

    @Override

    public void onDestroy()

    {

        Log.i(TAG, "ServiceonDestroy--->");

        //TODO: unregister broadcast

        super.onDestroy();

    }

    @Override

    public boolean onUnbind(Intent intent) {

        Log.i(TAG, "Serviceonunbind--->");

        return super.onUnbind(intent);

    }

    @Override

    public void onRebind(Intent intent) {

        Log.i(TAG, "Serviceonrebond--->");

        super.onRebind(intent);

    }

   @Override

    public IBinder onBind(Intent intent) {

        // TODO: Return the communicationchannel to the service.

       // throw new UnsupportedOperationException("Notyet implemented");

        return mBinder;

    }

    private final CloudServiceInterface.StubmBinder = new CloudServiceInterface.Stub() {

        @Override

        public void setInfo(int person)  {

            testdata = person;

        }

        @Override

        public int getInfo()   {

            return testdata;

        }

    };

}

然后点击project->clean,来编译项目。就会在gen目录里生成了CloudServiceInterface.aidl所用对应的CloudServiceInterface.java。如下:

然后在AndroidMannifest.xml里面添加服务声明:

<service

            android:name="com.rayleigh.cloud.CloudService"

            android:process=":remote"

            >

            <intent-filter >

                <action

                    android:name="com.rayleigh.cloud.CloudService"/>

            </intent-filter>

        </service>


然后在MainActivity.java里面定义服务对象:

CloudServiceInterfacemService;


    private ServiceConnectionserviceConnection =new ServiceConnection() {

        @Override

        publicvoid onServiceConnected(ComponentName componentName,IBinder iBinder) {

           Log.e("on","on service connected");

           mService = CloudServiceInterface.Stub.asInterface(iBinder);

        }


        @Override

        publicvoid onServiceDisconnected(ComponentName componentName) {

           Log.e("on","on service disconnected");

           mService = null;

        }

};


然后调用bindService函数启用服务。我定义成函数如下:

private void connectionToService() {

         Intent intent=newIntent(MainActivity.this,CloudService.class);

         this.getApplicationContext().bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);

  }

在onCreate里面调用此函数。


最后onCreate里面的内容如下:

    @Override

    protected void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        startBtn = (Button)findViewById(R.id.StartBtn);

        stopBtn = (Button) findViewById(R.id.StopBtn);


        startBtn.setOnClickListener(listener);

        stopBtn.setOnClickListener(listener);

        connectionToService();

}

其中按键点击响应函数如下:

private View.OnClickListener listener = newView.OnClickListener()

    {

        @Override

        public void onClick(Viewv)

        {

            switch (v.getId())

            {

                case R.id.StartBtn:

                    if (mService != null){

                        try {

                           mService.setInfo(3);

                            Log.e("mainactivity","setvalue success");

                        } catch (Exceptione){

                        }

                    } else {

                        Log.e("mainactivity","mServiceis null");

                    }

                    break;

                case R.id.StopBtn:


                    if (mService != null){

                        try {

                            int a= mService.getInfo();

                            Log.e("mainactivity","getvalue is :"+ a);

                        } catch (Exceptione) {

                        }

                    } else {

                        Log.e("mainactivity","mServiceis null");

                   }

                    break;

                default:

                    break;

            }

        }

    };


分别点击两个按键来,设置数字到服务里,和从服务里获取数据

这个例子很简单,看代码就可以了

转载于:https://www.jianshu.com/p/934246808bc6

Guess you like

Origin blog.csdn.net/weixin_33690963/article/details/91114992