Android在看到活动后做某事

时间:2013-09-23 16:49:20

标签: android android-asynctask android-activity progressdialog android-progressbar

我有一个按钮活动。当点击按钮时,一个新的活动开始,在这个活动中,从web获取各种数据。但是当我点击按钮时,第一个活动保持一段时间,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);
    }
}
}

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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任务,因此根据我的经验,在加载标记等之前等待一下会更好。此外,这应该能够让对话框在被解除之前正确显示。

相关问题