在android中获取此 RuntimeException
:
java.lang.RuntimeException:无法在Toast.makeText中调用Looper.prepare()得到运行时错误的线程内部创建处理程序(this,latitude“”longitude,1).show();
在函数 updateLocation()
中 .
public class Location_update extends Service {
double latitude;
double longitude;
GPSLocation gps;
boolean state=true;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Timer timer = new Timer();
timer.schedule(task, 0,1000*30);
}
TimerTask task=new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
updateLocation();
}
};
public void updateLocation()
{
gps = new GPSLocation(MainActivity.dis);
// check if GPS enabled
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
try
{
Toast.makeText(this, latitude+""+longitude, 1).show();
}
catch(Exception e)
{
Log.d("error", "msg:-- "+e);
}
// \n is for new line
//Toast.makeText(Location_update.this, "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
if(gps.getLatitude()!=0.0 && gps.getLongitude()!=0.0)
{
try {
String url = "http://surajsingh.freetzi.com/insert_longi_latti.php?latti="+latitude+"&longi="+longitude;
HttpGet get = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
JSONObject obj = new JSONObject(data);
int status = obj.getInt("status");
}
catch (Exception e) {
// TODO: handle exception
// Toast.makeText(Location_update.this, ""+e, 1).show();
Log.d("error", ""+e);
}
}
}
}
2 回答
你是从工作线程调用它 . 您需要从主线程中调用Toast.makeText() . 你可以使用一个处理程序 .
Sunny的回答是正确的 . 你需要使用
Handler
.在
Service
中创建Handler
.然后将消息传递给
Handler
,如下所示 .