我正在尝试通过处理程序获取 GPS 坐标。下面是代码:
final Thread ObainGpsBackground = new Thread(new Runnable() {
@Override
public void run() {
try{
String SetServerString = "";
//Obtaining GPS co-ordinates :
LatLong obj_latLong = new LatLong(getActivity());
addressList = obj_latLong.getListAddressFromGeocoder(getActivity());
//Setting the addressList.getLatitude() into a variable "SetServerString"
for (Address address : addressList) {
SetServerString = String.valueOf(address.getLatitude());
threadMsg(SetServerString);
}
//Obtaining GPS co-ordinates :
}
catch(Throwable t){
Log.i("Exception","Getting GPS exception : "+t);
}
}
});
不知何故,代码总是导航到 catch 块。我得到这个错误:
I/Exception: Getting GPS exception : java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
这是处理程序:
private void threadMsg(String setServerString) {
if (!setServerString.equals("") && !setServerString.equals("0")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", setServerString);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
// alert_attendance(getResources().getString(R.string.warning), getResources().getString(R.string.ects));
Toast.makeText(getActivity(), "Response: "+aResponse, Toast.LENGTH_SHORT).show();
}
else
{
// ALERT MESSAGE
alert_attendance(getResources().getString(R.string.warning), getResources().getString(R.string.unableToFindLocation));
// Toast.makeText(getBaseContext(), "Not Got Response From Server.", Toast.LENGTH_SHORT).show();
}
}
};
看过各种帖子。不知何故无法弄清楚。如何准确实现 looper.prepare() ?有任何想法吗 ?