我正在尝试在Google地图中显示位置地址,但是当我为获取地址启动Intent Service时,它将显示错误“无法实例化服务”。
我使用此链接显示位置地址。
https://developer.android.com/training/location/display-address.html
这是我的代码:
public class FetchAddressIntentService extends IntentService {
protected ResultReceiver mReceiver;
public FetchAddressIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
String errorMessage="";
Geocoder geocoder=new Geocoder(this, Locale.getDefault());
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
List<Address> addresses=null;
try {
addresses=geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
} catch (IOException e) {
errorMessage="unhendle IO exception";
e.printStackTrace();
}
if(addresses==null && addresses.size()==0){
if(errorMessage.isEmpty()){
errorMessage="no address found";
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
}
else{
Address address=addresses.get(0);
ArrayList<String> arrayListFrag=new ArrayList<>();
for (int i=0;i<address.getMaxAddressLineIndex();i++){
arrayListFrag.add(address.getAddressLine(0));
}
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"),
arrayListFrag));
}
}
private void deliverResultToReceiver(int successResult, String message) {
Bundle bundle=new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY,message);
mReceiver.send(successResult,bundle);
}
}
这里我开始意图服务:
protected void startIntentService(){
Intent intent=new Intent(this,FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA,mLastLocation);
startService(intent);
}
public void fetchAddressButtonHandler(){
if(mGoogleApiClient.isConnected() && mLastLocation!=null){
startIntentService();
}
}
答案 0 :(得分:1)
替换:
public FetchAddressIntentService(String name) {
super(name);
}
使用:
public FetchAddressIntentService() {
super("whatever you want to use here");
}
(用适合您应用的内容替换字符串)
答案 1 :(得分:1)
您需要向不带参数的类FetchAddressIntentService添加零参数构造函数:
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}