Клиент 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.");
}
}
}
Код: Выделить всё
Код: Выделить всё
// 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;
}
};
}
Код: Выделить всё
Проблема в том, что серверное приложение запускается, и я вижу сообщение «Сервис создан». войдите на серверную сторону, но когда я открываю клиентское приложение, оно говорит: «Не удалось привязать службу», поскольку эта кодовая фраза не работает
Код: Выделить всё
Intent intent = new Intent("com.example.aidl_service");
intent.setPackage("com.example.aidl_service"); // Explicitly set the package name
Intent explicitIntent = convertImplicitIntentToExplicitIntent(context, intent);
Подробнее здесь: https://stackoverflow.com/questions/793 ... tween-apps
Мобильная версия