Отправка объектов через AIDL через ParcelablesJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Отправка объектов через AIDL через Parcelables

Сообщение Anonymous »

У меня есть серверное и клиентское приложение, и я просто пытаюсь отправить объект с именем Component через AIDL с сервера на клиент.
Вот интерфейс AIDL AIDL .aidl:

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

// aidlInterface.aidl
package com.example.aidl_service;
import com.example.aidl_service.Component;

interface aidlInterface {
double[] getRandomLatLong(); // Existing method to get random location
void setNewLatLong(double lat, double lon); // New method to send modified location

// New methods for Component object
Component getComponent(); // Fetches the Component object
void setComponent(in Component component); // Sets the Component object
}

Компонент.aidl:

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

// Component.aidl
package com.example.aidl_service;
parcelable Component;
Код серверного приложения
Класс компонента Java, реализованный как метка посылки Component.java на сервере приложение:

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

package com.example.aidl_service;

import android.os.Parcel;
import android.os.Parcelable;

public class Component implements Parcelable {
private String name;
private double latitude;
private double longitude;

public Component(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
}

protected Component(Parcel in) {
name = in.readString();
latitude = in.readDouble();
longitude = in.readDouble();
}

public static final Creator  CREATOR = new Creator() {
@Override
public Component createFromParcel(Parcel in) {
return new Component(in);
}

@Override
public Component[] newArray(int size) {
return new Component[size];
}
};

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeDouble(latitude);
parcel.writeDouble(longitude);
}

// Getters and Setters
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getLatitude() {
return latitude;
}

public void setLatitude(double latitude) {
this.latitude = latitude;
}

public double getLongitude() {
return longitude;
}

public void setLongitude(double longitude) {
this.longitude = longitude;
}
}

Служебный файл сервера MyService.java:

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

package com.example.aidl_service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class MyService extends Service {

private Component component;

@Override
public IBinder onBind(Intent intent) {
return aidlBinder;
}

// AIDL Binder
private final aidlInterface.Stub aidlBinder = new aidlInterface.Stub() {

// Existing methods for location
@Override
public double[] getRandomLatLong() throws RemoteException {
return new double[]{getRandomLatitude(), getRandomLongitude()};
}

@Override
public void setNewLatLong(double lat, double lon) throws RemoteException {
// Set new lat/long logic (already implemented)
}

// New AIDL methods to handle Component object
@Override
public Component getComponent() throws RemoteException {
if (component == null) {
// Generate a default component if null
component = new Component("Default", getRandomLatitude(), getRandomLongitude());
}
return component;
}

@Override
public void setComponent(Component component) throws RemoteException {
MyService.this.component = component;
}
};

// Generate random latitude
private double getRandomLatitude() {
return Math.random() * 180 - 90;
}

// Generate random longitude
private double getRandomLongitude() {
return Math.random() * 360 - 180;
}
}

Наконец, основная активность сервера MainActivity.java:

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

package com.example.aidl_service;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static MainActivity instance;

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

instance = this;
}

// Singleton pattern to access the activity instance
public static MainActivity getInstance() {
return instance;
}
}

Код клиентского приложения
Клиентское приложение имеет тот же вспомогательный код и файлы, что и серверное приложение, вот основная активность клиентского приложения MainActivity.java:

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

package com.example.aidl_client;

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

import com.example.aidl_service.Component;  // ERROR IN IMPORTING
import com.example.aidl_service.aidlInterface;

public class MainActivity extends Activity {

private TextView latDisplay, longDisplay, nameDisplay;
private Button getComponentButton, setComponentButton;
private Context mContext;

private aidlInterface aidlInterfaceObject;

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

// Initialize the UI components
mContext = this;
latDisplay = findViewById(R.id.lat_display);
longDisplay = findViewById(R.id.long_display);
nameDisplay = findViewById(R.id.name_display); // New TextView for Component name
getComponentButton = findViewById(R.id.get_location_button);
setComponentButton = findViewById(R.id.set_location_button);

// Set up button to get component
getComponentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fetchComponent();
}
});

// Set up button to send modified component
setComponentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendModifiedComponent();
}
});

// Bind to the AIDL service
bindAIDLService();
}

// Fetch component from the service
private void fetchComponent() {
if (aidlInterfaceObject != null) {
try {
// Fetch component object
Component component = aidlInterfaceObject.getComponent();
nameDisplay.setText("Component Name: " + component.getName());
latDisplay.setText("Latitude: " + component.getLatitude());
longDisplay.setText("Longitude: " + component.getLongitude());
} catch (RemoteException e) {
e.printStackTrace();
Toast.makeText(mContext, "Error fetching component", Toast.LENGTH_SHORT).show();
}
}
}

// Send modified component to the service
private void sendModifiedComponent() {
if (aidlInterfaceObject != null) {
try {
// Create a new modified component
Component component = new Component("Modified", 12.34, 56.78);
aidlInterfaceObject.setComponent(component);

Toast.makeText(mContext, "Component sent to service", Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
Toast.makeText(mContext, "Error sending component", Toast.LENGTH_SHORT).show();
}
}
}

// Bind to the AIDL service
private void bindAIDLService() {
Intent intent = new Intent("com.example.aidl_service");
bindService(convertImplicitIntentToExplicitIntent(intent, mContext), serviceConnection, BIND_AUTO_CREATE);
}

private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
aidlInterfaceObject = aidlInterface.Stub.asInterface(iBinder);
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
aidlInterfaceObject = null;
}
};

public Intent convertImplicitIntentToExplicitIntent(Intent implicitIntent, Context context) {
PackageManager packageManager = context.getPackageManager();
List  resolveInfoList = packageManager.queryIntentServices(implicitIntent, 0);
if (resolveInfoList == null || resolveInfoList.size() != 1) {
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;
}
}

Я собираю и запускаю серверное приложение, и оно работает нормально, но я не могу создать клиентское приложение, поскольку получаю следующую ошибку:

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

error: cannot find symbol
import com.example.aidl_service.Component;
^
symbol:   class Component
location: package com.example.aidl_service
Насколько я понимаю, класс Component должен автоматически генерироваться в клиентском приложении, когда я запускаю серверное приложение. Я новичок в AIDL, поэтому, вероятно, мне не хватает чего-то очень тривиального. Это полный код проблемы! Любая помощь будет здорово! Спасибо!

Подробнее здесь: https://stackoverflow.com/questions/790 ... arcelables
Ответить

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

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

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

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

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