0

我有一个带有按钮的活动。单击按钮时,会启动一个新活动,并且在此活动中,会从网络获取各种数据。但是当我单击按钮时,第一个活动会持续一段时间,然后 3-4 秒后第二个活动开始准备好数据。显然,在第二个活动可见之前,应用程序会尝试获取数据。但首先,我希望第二个活动对用户可见,之后必须开始获取数据。我检查了活动生命周期并将获取替换为 onStart() 但不起作用

 @Override
 protected void onStart() {
          super.onStart();
          //Fetch data
 }

我怎样才能做到这一点 ?

这是我的所有代码(只是第二个活动):

public class GuzergahActivity extends android.support.v4.app.FragmentActivity{

      private GoogleMap map;
      private GuzergahOverlay overlay;
      private WebView webview;
      private ImageView imageview;
      private ProgressDialog dialog;
      private int flag;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        overridePendingTransition(0, 0);
        setContentView(R.layout.guzergah);
        flag=this.getIntent().getExtras().getInt("flag");
        setUpMapIfNeeded();
        setUpView();
      }

      @Override
      protected void onResume() {
          super.onResume();
          setUpMapIfNeeded();
      }

      @Override 
      protected void onDestroy() {
        if (dialog!=null) {
            dialog.dismiss();
        }
        super.onDestroy();
      }

      private void setUpMapIfNeeded() {
            // Do a null check to confirm that we have not already instantiated the map.
            if (map == null) {
                map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.guzergah_fragment)).getMap();
                if(map!=null){
                    setUpMap();
                }
            }
      }

    private void setUpMap(){

         try {
            String result=new MyNewTask().execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         overlay.setOverlay(map);
         map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.910526,32.804435),15));
         map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
    }


    private void setUpView() {
           //Binding imageview,webview...and setting up their features
    }

    private class MyNewTask extends AsyncTask<String,Integer,String> 
    {
        @Override
        protected void onPreExecute()
        {

            dialog= new ProgressDialog(GuzergahActivity.this);
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.setMessage("Downloading! Please wait...!");
            dialog.show();

        }


        @Override
        protected String doInBackground(String... params)
        {
            /* Fetching data is in this class - GuzergahOverlay*/ 
            overlay =  new GuzergahOverlay(flag);

            return "Done";

      }

        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
            Log.i("result","" +result);
            if(result!=null){
                dialog.dismiss();
            }
        }

    } //end MyNewTask
}



public class GuzergahOverlay {

private MarkerOptions beytepe_kampusu;
private MarkerOptions sihhiye_kampusu;
private ArrayList<PolylineOptions> lines;
private ArrayList<MarkerOptions> stops;

public GuzergahOverlay(int mode) {
    beytepe_kampusu=new MarkerOptions().position(new LatLng(39.87159,32.735435)).title("Hacettepe Üniversitesi Beytepe Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_beytepe));
    sihhiye_kampusu=new MarkerOptions().position(new LatLng(39.931599,32.862365)).title("Hacettepe Üniversitesi Sıhhıye Yerleşkesi").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_sihhiye));
    getLinesAndStops(mode); //Here is fetching geopoint and preparing lines and stops arraylists
}

private void getLinesAndStops(int mode) {

    // Fetching data from Parse.com
            // Fillinp up lines and stops arraylists
}




public void setOverlay(GoogleMap map){
    map.addMarker(beytepe_kampusu);
    map.addMarker(sihhiye_kampusu);
    for(PolylineOptions polyline : lines){
        map.addPolyline(polyline);
    }
    for(MarkerOptions marker : stops){
        map.addMarker(marker);
    }
}
}

使用上面的代码,当我单击按钮时,第一个活动会持续一段时间,当获取数据完成时,第二个活动是可见的。进度对话框只显示几毫秒

4

2 回答 2

1

您应该将数据获取方法移动到AsyncTask中。您永远不应该从 UI 线程上的远程源获取数据。如果您以这种方式将该操作移至后台线程,则 UI 将具有更高的优先级,并且应该快速加载,同时仍然允许您的异步任务完成。您甚至可以在 onCreate 或 onStart 中启动任务,您应该会看到更好的性能。

于 2013-09-23T16:55:51.250 回答
1

听起来好像您正在 UI 线程中运行所有代码。如果有更多的代码能够给出一个更好的例子,那就太好了。

在您的第二个活动中:

    private class BackgroundTask extends AsyncTask<Void, Void, Void> {

    // Before running code in separate thread
    @Override
    protected void onPreExecute() {
        // setup loading dialog
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // do long running code
        return null;
    }

    // after executing the code in the thread
    @Override
    protected void onPostExecute(Void arg) {
        // dismiss your dialog

    }

}

在 onCreate 里面:

new BackgroundTask().execute();

编辑:

现在我已经看到了你的代码,我建议你尝试这样的事情:

    private void setUpMap(){
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new      LatLng(39.910526,32.804435),15));
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                try {
                    String result = new MyNewTask().execute();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                /*
                 * you should move this call to onPostExecute
                 * then you will not need to call execute().get() 
                 * which takes away the advantage of AsyncTask
                 * as it then is run on UI thread
                 */

                overlay.setOverlay(map);
            }
        }, 2000);

    }

设置地图是一项繁重的 UI 任务,因此根据我的经验,在加载标记等之前稍等片刻看起来会更好。此外,这应该使对话框能够在关闭之前正确显示。

于 2013-09-23T17:02:38.577 回答