Вызов метода в сервисе, который находится в другом приложении, используя помощь

Я следую методу, описанному в Поваренной книге разработчика Android. Вот мой интерфейс помощи

пакет com.test.aidl;

interface IMyAidl{

    int add(int n1, int n2 );
}

Мой класс обслуживания

package com.test.usingaidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;

import com.test.aidl.IMyAidl;

/**
 * Created by HarshVardhan on 1/18/2016.
 */
public class AddService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private final IMyAidl.Stub mBinder = new IMyAidl.Stub() {
        @Override
        public int add(int n1, int n2) throws RemoteException {
            return n1+n2;
        }
    };


}

Моя основная активность

package com.test.usingaidl;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.test.aidl.IMyAidl;

public class MainActivity extends AppCompatActivity {

    IMyAidl service;
    MServiceConnection con;

    class MServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder bound) {
            service =IMyAidl.Stub.asInterface(bound);
            Toast.makeText(MainActivity.this,"Service Connected!",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service = null;
            Toast.makeText(MainActivity.this,"Service Disconnected!",Toast.LENGTH_LONG).show();
        }
    }

    private void initService(){
        con = new MServiceConnection();
        Intent i = new Intent();
        i.setClassName(this, com.test.usingaidl.AddService.class.getName());
        if(!bindService(i, con, Context.BIND_AUTO_CREATE)){
            Toast.makeText(this, "Bind Service Failed!", Toast.LENGTH_SHORT).show();
        }
    }

    private void releaseService(){
        unbindService(con);
        con = null;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initService();
        Button b = (Button) findViewById(R.id.button);
        final EditText et1 = (EditText) findViewById(R.id.editText);
        final EditText et2 = (EditText) findViewById(R.id.editText2);
        final TextView tv = (TextView) findViewById(R.id.textView);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int i = service.add(Integer.parseInt(et1.getText().toString()),Integer.parseInt(et2.getText().toString()));
                    tv.setText(i+"");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}

и манифест

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.usingaidl">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".AddService" android:process=":remoteService">
            <intent-filter >
                <action android:name="com.test.usingaidl.addService"></action>
            </intent-filter>
        </service>
    </application>

</manifest>

У меня есть два EditText, и я получаю два числа и добавляю их с помощью службы. В этом примере он отлично работает, так как интерфейс и служба находятся в одном пакете. Но я хочу использовать сервис и вызывать метод в другом действии. Я много искал, но ответы, которые я нашел, были не такими полезными.


person Rookie    schedule 20.01.2016    source источник


Ответы (1)


Итак, после долгих поисков я наконец нашел ответ. Проблема заключалась в том, что мне нужно было иметь вспомогательный файл клиентского и серверного приложений в одном и том же имени пакета.

person Rookie    schedule 25.01.2016
comment
Можете ли вы поделиться своими фрагментами кода, как вы этого добились, чтобы это было полезно для начинающих, таких как я. - person vgokul129; 02.01.2018