【问题标题】:Android Doing something AFTER Activity is visibleAndroid Doing something AFTER Activity 可见
【发布时间】:2013-09-28 16:03:04
【问题描述】:

我有一个带有按钮的活动。单击按钮时,会启动一个新活动,并且在此活动中,从网络获取各种数据。但是当我单击按钮时,第一个活动会持续一段时间并在 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);
    }
}
}

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

【问题讨论】:

  • 如果我成功了,也许我在第二个活动中的进度对话框会出现

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


【解决方案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 任务,因此根据我的经验,在加载标记等之前稍等片刻看起来会更好。此外,这应该可以让对话框在关闭之前正确显示。

【讨论】:

  • 是的。所有将标记添加到地图等的调用都必须在 UI 线程上,但可以在 onPostExcecute 中。认为你应该移动 super.onPostExecute(result);到方法的底部。
  • 我已经更新了我的答案,希望你能得到你正在寻找的行为
  • 它给了我编译错误“赋值的左侧必须是一个变量”对于新的处理程序.....代码。我输入了处理程序 hnd = 新处理程序...... . 但没有任何改变
  • 抱歉,我输入密码时一定有什么东西漏掉了,现在试试。
  • 现在,Acitivity 会立即打开,这很好,但 ProgressDialog 没有出现。在添加线条和标记之前,它会在很短的时间内变得可见。不管我感谢你的工作。谢谢跨度>
【解决方案2】:

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

【讨论】:

  • 感谢回复,我用代码编辑了我的问题。你能再看看吗?
  • @SedatKURT 您的编辑看起来正朝着正确的方向前进。现在有什么问题?
  • 我在问题的最后说“使用上面的代码,当我点击按钮时,第一个活动会持续一段时间,当获取数据完成时第二个活动是可见的。进度对话框仅显示几个毫秒”。这是我的问题:(
猜你喜欢
  • 2022-12-02
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 2012-07-24
相关资源
最近更新 更多