我构建这个应用程序只是为了学习android。当我尝试在其上调用方法时,它表示服务绑定为null。编译正常并在运行时失败。谢谢你的帮助!
将loadAnimals()移动到onServiceConnected()后出现新错误:
11-14 11:09:50.610 2978-2978/? E/AndroidRuntime: java.lang.RuntimeException: Unable to resume activity {com.jacob_w.animalList/com.jacob_w.animalList.MainActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.jacob_w.animalList.IAnimalInterface }
主要逻辑片段:
public class AnimalListFragment extends ListFragment implements ServiceConnection {
IAnimalInterface mAnimalInterfaceBinder = null;
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnimalInterfaceBinder = IAnimalInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mAnimalInterfaceBinder = null;
}
@Override
public void onResume() {
super.onResume();
getActivity().bindService(new Intent("com.jacob_w.animalList.IAnimalInterface"), this,
Context.BIND_AUTO_CREATE);
}
@Override
public void onPause() {
getActivity().unbindService(this);
super.onPause();
}
public void loadAnimals() {
SystemClock.sleep(2000);
AnimalList animalList;
try {
animalList = mAnimalInterfaceBinder.getAnimalList();
}
catch (RemoteException e) {}
}
}
AIDL界面:
import com.jacob_w.animalList.AnimalList;
interface IAnimalInterface {
AnimalList getAnimalList();
}
对象定义:
parcelable AnimalList;
服务:
public class AnimalService extends Service {
private AnimalList animalList = null;
@Override
public IBinder onBind(Intent intent) {
return mAnimalInterfaceBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_REDELIVER_INTENT;
}
public void updateAnimals() {
return animalList; // Stub
}
private final IAnimalInterface.Stub mAnimalInterfaceBinder = new IAnimalInterface.Stub() {
public AnimalList getAnimalList() {
return animalList;
}
}
}
对象:
public final class AnimalList implements Parcelable {
public String[] animals;
public String[] links;
public AnimalList(String[] animals, String[] links) {
this.animals = animals;
this.links = links;
}
public static final Creator<AnimalList> CREATOR = new Creator<AnimalList>() {
@Override
public AnimalList createFromParcel(Parcel source) {
return new AnimalList(source);
}
@Override
public AnimalList[] newArray(int size) {
return new AnimalList[size];
}
};
private AnimalList(Parcel animalParcel) {
animals = animalParcel.createStringArray();
links = animalParcel.createStringArray();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(animals);
dest.writeStringArray(links);
}
}