我正在使用异步任务并搜索我的gps位置(使用网络提供商)我在locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
public class SimpleDirect extends MapActivity {
MapView mapView;
private ProgressDialog pDialog;
private LocationManager locManager;
private LocationListener locListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_direct_main);
mapView = (MapView)findViewById(R.id.mapView);
initMap();
new Activity().execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SimpleDirect.this);
pDialog.setMessage("Mohon tunggu...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
initLocationManager();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
private void initLocationManager(){
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
public void onLocationChanged(Location newLocation) {
tampilkanPosisikemap(newLocation);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0){
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
protected void tampilkanPosisikemap(Location newLocation) {
List overlays = mapView.getOverlays();
if(overlays.size() > 0) {
for(Iterator iterator = overlays.iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
}
GeoPoint geopoint = new GeoPoint(
(int) (newLocation.getLatitude() * 1E6), (int) (newLocation
.getLongitude() * 1E6));
Drawable icon = getResources().getDrawable(R.drawable.marker);
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
MyItemizedOverlay overlay = new MyItemizedOverlay(icon);
OverlayItem item = new OverlayItem(geopoint, "My Location", null);
overlay.addItem(item);
mapView.getOverlays().add(overlay);
mapView.getController().animateTo(geopoint);
mapView.postInvalidate();
}
private void initMap() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.getController().setZoom(15);
}
@Override
protected boolean isRouteDisplayed(){
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.simple_direct_main, menu);
return true;
}
}
我的logcat:
04-22 20:48:26.763: E/AndroidRuntime(15676): FATAL EXCEPTION: AsyncTask #1
04-22 20:48:26.763: E/AndroidRuntime(15676): java.lang.RuntimeException: An error occured while executing doInBackground()
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.os.AsyncTask$3.done(AsyncTask.java:200)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.lang.Thread.run(Thread.java:1096)
04-22 20:48:26.763: E/AndroidRuntime(15676): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.os.Handler.<init>(Handler.java:121)
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:139)
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
04-22 20:48:26.763: E/AndroidRuntime(15676): at com.example.simpledirection.SimpleDirect.initLocationManager(SimpleDirect.java:128)
04-22 20:48:26.763: E/AndroidRuntime(15676): at com.example.simpledirection.SimpleDirect.access$2(SimpleDirect.java:107)
04-22 20:48:26.763: E/AndroidRuntime(15676): at com.example.simpledirection.SimpleDirect$Activity.doInBackground(SimpleDirect.java:93)
04-22 20:48:26.763: E/AndroidRuntime(15676): at com.example.simpledirection.SimpleDirect$Activity.doInBackground(SimpleDirect.java:1)
04-22 20:48:26.763: E/AndroidRuntime(15676): at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-22 20:48:26.763: E/AndroidRuntime(15676): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-22 20:48:26.763: E/AndroidRuntime(15676): ... 4 more
04-22 20:48:26.813: E/MapActivity(15676): Couldn't get connection factory client
04-22 20:48:27.623: E/WindowManager(15676): Activity com.example.simpledirection.SimpleDirect has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4a0aa048 that was originally added here
04-22 20:48:27.623: E/WindowManager(15676): android.view.WindowLeaked: Activity com.example.simpledirection.SimpleDirect has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4a0aa048 that was originally added here
04-22 20:48:27.623: E/WindowManager(15676): at android.view.ViewRoot.<init>(ViewRoot.java:247)
04-22 20:48:27.623: E/WindowManager(15676): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
04-22 20:48:27.623: E/WindowManager(15676): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
04-22 20:48:27.623: E/WindowManager(15676): at android.view.Window$LocalWindowManager.addView(Window.java:424)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.Dialog.show(Dialog.java:241)
04-22 20:48:27.623: E/WindowManager(15676): at com.example.simpledirection.SimpleDirect$Activity.onPreExecute(SimpleDirect.java:88)
04-22 20:48:27.623: E/WindowManager(15676): at android.os.AsyncTask.execute(AsyncTask.java:391)
04-22 20:48:27.623: E/WindowManager(15676): at com.example.simpledirection.SimpleDirect.onCreate(SimpleDirect.java:59)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2633)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.ActivityThread.access$2300(ActivityThread.java:126)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
04-22 20:48:27.623: E/WindowManager(15676): at android.os.Handler.dispatchMessage(Handler.java:99)
04-22 20:48:27.623: E/WindowManager(15676): at android.os.Looper.loop(Looper.java:123)
04-22 20:48:27.623: E/WindowManager(15676): at android.app.ActivityThread.main(ActivityThread.java:4633)
04-22 20:48:27.623: E/WindowManager(15676): at java.lang.reflect.Method.invokeNative(Native Method)
04-22 20:48:27.623: E/WindowManager(15676): at java.lang.reflect.Method.invoke(Method.java:521)
04-22 20:48:27.623: E/WindowManager(15676): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
04-22 20:48:27.623: E/WindowManager(15676): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-22 20:48:27.623: E/WindowManager(15676): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
答案就在那里,David Olsson已经提到过。您在mapView.postInvalidate();
中正在doInBackground
。 doInBackground不允许UI工作。对于UI工作,您需要使用onPre,或者使用onPost。
例外就是说
引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
答案 1 :(得分:0)
你不应该在locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
内调用AsyncTask
,而应该在一个单独的线程上调用public void onLocationChanged(Location newLocation) {
内的代码。
requestLocationUpdates
是非同步的非阻塞调用,不需要您添加线程。您的AsyncTask
会立即结束。
除此之外,我建议不要有像这样的代码结构。请注意,每次找到位置时,您都将启动AsyncTask。如果您旋转设备或完成此Activity
,您最终会在同一时间启动许多内存泄漏。
答案 2 :(得分:0)
此代码适用于我 您可以在异步
中获取位置public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mw = new Mywidgets(getApplicationContext());
progressDialog = new ProgressDialog(MapsActivity.this);
try
{
progressDialog.setMessage("Loading Please wait");
Load_task load_task = new Load_task();
load_task.execute();
}catch (Exception e){
mw.app_log(e.getMessage());
}
}
public class Load_task extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
Bundle bun = getIntent().getExtras();
final String location = bun.getString("location");
location_arr = location.split(",");
Geocoder gc = new Geocoder(getApplicationContext());
List<Address> addresses = new LinkedList<>();
int c = 0;
for (String loc : location_arr) {
// mw.app_log(loc);
List<Address> each_addr = null;
try {
each_addr = gc.getFromLocationName(loc, 1);
} catch (IOException e) {
mw.app_log("cant get location");
e.printStackTrace();
}
addresses.add(each_addr.get(0));
}
lat_long = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
for (Address a : addresses) {
if (a.hasLatitude() && a.hasLongitude()) {
lat_long.add(new LatLng(a.getLatitude(), a.getLongitude()));
mw.app_log("added "+lat_long.toString());
}else{
mw.app_log("not added");
}
}
return null;
}
@Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
progressDialog.hide();
mw.app_log(lat_long.toString());
set_map();
super.onPostExecute(aVoid);
}
}
public void set_map(){
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (Geocoder.isPresent()) {
try {
progressDialog.hide();
//addresses.remove(0);
// Add a marker in Sydney and move the camera
int n = 0;
for (LatLng lat : lat_long) {
MarkerOptions marker = new MarkerOptions().position(lat).title(location_arr[n++]);
marker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.eauction_car_icon_map)).position(lat).snippet(location_arr[n - 1]);
mMap.addMarker(marker);
}
mMap.moveCamera(CameraUpdateFactory.newLatLng(lat_long.get(2)));
;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lat_long.get(0), 12.0f));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
Intent prop_intent = new Intent(getApplicationContext(), Property_view.class);
int pos = Integer.parseInt(marker.getId().substring(1));
//prop_intent.putExtra("location",location[pos]);
mw.toast(location_arr[pos]);
// startActivity(prop_intent);
return false;
}
});
//mMap.setOnCameraIdleListener(mClusterManager);
} catch (Exception e) {
Log.d("json_obj", e.getMessage());
}
}
}