在下面的代码中,我试图将活动实例传递给GPSService并在两个上下文之间形成弱引用。 但是在运行时,我收到以下错误,这表明无法将getApplicationContext()强制转换为MainActivity
请让我知道如何将mainActivity的实例传递给服务。
代码:
AVLTree
服务:
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "GPS_READINGS", Toast.LENGTH_SHORT).show();
GPSService gpsService = new GPSService((MainActivity) getApplicationContext());
Intent intentStartGPSService = new Intent(getApplicationContext(), GPSService.class);
intentStartGPSService.setAction(ACTION_START_GPS_READING);
startService(intentStartGPSService);
}
});
错误:
public GPSService(Context mainActivity) {
this.mWeakRefToMainActivity = new WeakReference<>((MainActivity) mainActivity);
}
//causes the same error
/*public GPSService(MainActivity mainActivity) {
this.mWeakRefToMainActivity = new WeakReference<>((MainActivity) mainActivity);
}*/