AIDL-коммуникация между приложениямиAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 AIDL-коммуникация между приложениями

Сообщение Anonymous »

Я пытаюсь связаться с двумя приложениями Android, работающими на эмуляторе (Android 11 Pixel 4a API30), через Aidl, но мое клиентское приложение не может привязаться. Вот мои коды:
Клиент MainActivity.java

Код: Выделить всё

package com.example.aidl_service;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ResolveInfo;
import android.os.IBinder;

import com.example.aidl_service.IMyAidlInterface;

import java.util.List;

public class MainActivity extends AppCompatActivity {

Context context;
private IMyAidlInterface aidlService;

private final String TAG = "ClientMainAct";

// Define the ServiceConnection for connecting to the AIDL Service
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
aidlService = IMyAidlInterface.Stub.asInterface(iBinder);
Toast.makeText(context, "Service Connected", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Service connected.");
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
aidlService = null;
Toast.makeText(context, "Service Disconnected", Toast.LENGTH_SHORT).show();
Log.w(TAG, "Service disconnected.");
}
};

// Bind to the AIDL Service
private void bindAIDLService() {
try {
Intent intent = new Intent("com.example.aidl_service");
intent.setPackage("com.example.aidl_service"); // Explicitly set the package name
Intent explicitIntent = convertImplicitIntentToExplicitIntent(context, intent);

if (explicitIntent != null) {
bindService(explicitIntent, serviceConnection, BIND_AUTO_CREATE);
Log.i(TAG, "Attempting to bind to the service.");
} else {
Log.e(TAG, "Explicit Intent conversion failed.  Service may not exist.");
Toast.makeText(context, "Failed to bind service.", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e(TAG, "Error while binding service: ", e);
}
}

// Convert Implicit Intent to Explicit Intent
private Intent convertImplicitIntentToExplicitIntent(Context context, Intent implicitIntent) {
List resolveInfoList = context.getPackageManager().queryIntentServices(implicitIntent, 0);
if (resolveInfoList == null || resolveInfoList.size() != 1) {
Log.w(TAG, "Implicit Intent resolution failed or resolved to multiple services.");
return null;
}

ResolveInfo serviceInfo = resolveInfoList.get(0);
ComponentName component = new ComponentName(serviceInfo.serviceInfo.packageName, serviceInfo.serviceInfo.name);
Intent explicitIntent = new Intent(implicitIntent);
explicitIntent.setComponent(component);
return explicitIntent;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;

// Button setup and click listener
Button button = findViewById(R.id.button2);
button.setOnClickListener(v -> {
if (aidlService != null) {
try {
// Send a request to the AIDL service
String response = aidlService.concat("a", "b");

Toast.makeText(this, "Response: " + response, Toast.LENGTH_SHORT).show();
Log.i(TAG, "Response from Service: " + response);
} catch (RemoteException e) {
Log.e(TAG, "Error communicating with the service", e);
Toast.makeText(this, "Error communicating with the service", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Service not bound!", Toast.LENGTH_SHORT).show();
Log.w(TAG, "Service not bound!");
}
});

bindAIDLService(); // Bind to the service on app launch
}

@Override
protected void onDestroy() {
super.onDestroy();
if (serviceConnection != null) {
unbindService(serviceConnection); // Unbind the service when the activity is destroyed
Log.i(TAG, "Service unbound.");
}
}
}

Манифест клиента Android Мой помощник

Код: Выделить всё

// IMyAidlInterface.aidl
package com.example.aidl_service;

// Declare any non-default types here with import statements

interface IMyAidlInterface {
String concat(String s, String s1);
}
Основное действие сервера.

Код: Выделить всё

package com.example.aidl_service;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.Intent;

public class MainActivity extends AppCompatActivity {

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

Intent intent = new Intent(this, MyService.class);
startService(intent);

}
}
Серверная служба

Код: Выделить всё

package com.example.aidl_service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

private static final String TAG = "MyAidlService";

@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service created.");
}

@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "Service bound.");
return binder;
}

@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "Service unbound.");
return super.onUnbind(intent);
}

private final IMyAidlInterface.Stub binder = new IMyAidlInterface.Stub() {
@Override
public String concat(String str1, String str2) {
Log.d(TAG, "concat called with: " + str1 + " and " + str2);
return str1 + str2;
}
};
}

Манифест Android сервера Если хотите, я могу поделиться своими файлами сборки Gradle.
Проблема в том, что серверное приложение запускается, и я вижу сообщение «Сервис создан». войдите на серверную сторону, но когда я открываю клиентское приложение, оно говорит: «Не удалось привязать службу», поскольку эта кодовая фраза не работает

Код: Выделить всё

Intent intent = new Intent("com.example.aidl_service");
intent.setPackage("com.example.aidl_service"); // Explicitly set the package name
Intent explicitIntent = convertImplicitIntentToExplicitIntent(context, intent);

Я пытаюсь связаться с двумя приложениями Android с помощью Aidl, но мое клиентское приложение не распознает сервер.

Подробнее здесь: https://stackoverflow.com/questions/793 ... tween-apps
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»