Ok, jestem nowy w rozwoju Androida i próbuję powiązać usługę, aby móc wywoływać metody w usłudze po jej uruchomieniu. Opisane poniżej działanie i usługa są częścią tej samej aplikacji, więc nie powinno być żadnych problemów, ale za każdym razem, gdy uruchomię swoją aplikację, pojawia się następujący błąd:Wyjątek Android ClassCast podczas wiązania z usługą
java.lang.ClassCastException: android.os.BinderProxy
linia ta dzieje się na to:
LocalBinder binder = (LocalBinder) service;
Mój kod aktywny (uproszczony jest):
public class Main extends Activity {
boolean gpsBound = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called whenever the activity is started. */
@Override
protected void onStart() {
super.onStart();
// Bind to GPSService
Intent i = new Intent(this, GPSService.class);
startService(i);
bindService(i, connection, Context.BIND_AUTO_CREATE);
}
/** service binding */
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// After binding to GPSService get the instance of it returned by IBinder
LocalBinder binder = (LocalBinder) service;
gpsBound = true;
}
public void onServiceDisconnected(ComponentName className) {
gpsBound = false;
}
};
}
Usługa:
public class GPSService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent i) {
// TODO Auto-generated method stub
return new LocalBinder<GPSService>(this);
}
/**
* Our implementation of LocationListener that handles updates given to us
* by the LocationManager.
*/
public class CustomLocationListener implements LocationListener {
DBHelper db;
CustomLocationListener() {
super();
}
// Overridden methods here...
}
}
I wreszcie moja LocalBinder:
/**
* A generic implementation of Binder to be used for local services
* @author Geoff Bruckner 12th December 2009
*
* @param <S> The type of the service being bound
*/
public class LocalBinder<S> extends Binder {
private String TAG = "LocalGPSBinder";
private WeakReference<S> mService;
public LocalBinder(S service){
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
rozumiem rozumieniu wyjątku ClassCast ale nie mogę zrozumieć, co robić! Podążyłem za przykładem w dokumentacji Google, ale nadal nie działa. Czy ktoś może rzucić jakiekolwiek światło na to, co może być przyczyną tego?
Z góry dziękuję!
Czy oznacza podoba: „LocalBinder spoiwo = (LocalBinder ) Usługi;” Jeśli tak, to nadal daje ten sam błąd! –
Byłem skłonny do całkowitego usunięcia generyków. Będę edytować w krótkim przykładzie użycia usługi boundService, którą teraz piszę. –
Będzie można samemu przejść bez generycznych, ale jeśli mógłbyś podać przykład, który byłby świetny!Dzięki, James –