满足条件时自动启动asynctask

时间:2014-07-10 11:30:47

标签: android android-asynctask alertdialog

当您点击按钮时,此应用会搜索您周围的景点。流程是这样的:

  • 点击按钮搜索
  • 它检查互联网连接,如果没有,你得到一个对话询问 你启用互联网
  • 点击按钮搜索
  • 它检查位置服务,如果没有,你会得到一个对话框询问你 启用位置跟踪并将您带到Gps设置屏幕
  • 然后你回去,点击按钮搜索和asynctask开始 做这项工作(搜寻和展示)

我需要做的是取消按钮搜索,因此它会一步一步地自动完成所有操作。所以它会像:

  • 启动应用
  • 它检查互联网连接,如果没有,你得到一个对话询问 你启用互联网
  • 启用互联网后,它会检查位置服务,如果没有,则会出现一个对话框,要求您启用位置跟踪并转到Gps设置屏幕
  • 然后启动asynctask

我虽然这个警告对话框会让活动暂停,我可以检查所有条件,但看起来没有。我该怎么解决这个问题?随意询问任何更多细节。

忘记提及我只想要这样做一次,第一次启动应用

这是我的代码:

public class MainActivity extends Activity {
    //variables

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView) findViewById(R.id.list);
        button = (Button) findViewById(R.id.btn_show_map);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                cd = new ConnectionDetector(MainActivity.this);

                // Check if Internet present
                isInternetPresent = cd.isConnectingToInternet();
                if (!isInternetPresent) {
                    // Internet Connection is not present
                    alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to a working Internet connection", false);
                    return;
                }

                // creating GPS Class object
                gps = new GPSTracker(MainActivity.this);

                // check if GPS location can get
                if (gps.canGetLocation()) {
                    Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
                } else {
                    // Can't get user's current location
                    gps.showSettingsAlert();
                    return;
                }

                new LoadPlaces().execute();
            }
        });
    }

    class LoadPlaces extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {
            Long t = Calendar.getInstance().getTimeInMillis();
            while (!gps.hasLocation && Calendar.getInstance().getTimeInMillis() - t < 60000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // get the places

            return null;
        }

        protected void onPostExecute(String file_url) {

            // dismiss the dialog after getting all products
            pDialog.dismiss();
            gps.stopUsingGPS();

            // display the results
        }
    }
}

更新:我在想,根据我在下面写的内容,可能会有更好的选择与不同的主题。或者也许是服务或接收者......有什么想法吗?

Thread th = new Thread() {
            boolean allEnabled = false;

            @Override
            public void run() {
                Long t = Calendar.getInstance().getTimeInMillis();
                while (!allEnabled && Calendar.getInstance().getTimeInMillis() - t < 120000) {
                    try {
                        isInternetPresent = cd.isConnectingToInternet();
                        if (!isInternetPresent) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to a working Internet connection", false);
                                }
                            });
                        } else if (!gps.canGetLocation()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    gps.showSettingsAlert();
                                }
                            });
                        } else {
                            allEnabled = true;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new LoadPlaces().execute();
                                }
                            });
                        }
                        Thread.sleep(20000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        th.start();

这个版本当然不行,因为它会一个接一个地阻塞一个对话框。

2 个答案:

答案 0 :(得分:2)

通常这样的事情可以通过活动中的几个回调/入口点来解决。为此,您需要构建自己的AltertDialogs - 一个用于提示用户启用互联网,一个用于提示用户启用GPS。对于对话框,您必须为NegativeButtonPositiveButton设置操作。

逻辑看起来像这样:

                                                               NegativeButton -> Exit App
                            Disabled -> Prompt user to enable {
OnCreate -> Check internet {                                   PositiveButton -> Go to Check GPS
                            |
                            |                                                          NegativeButton -> Exit App
                            |                       Disabled -> Prompt user to enable {
                            *-Enabled -> Check GPS {                                   PositiveButton -> Start AsyncTask
                                                    Enabled -> Start AsyncTask

您可以实现&#34;转到&#34;作为OnClickListener PositiveButtons中调用的函数。

这就是让Android成为Callback-hell的原因,但我还没有为这样的东西找到更好的解决方案。我希望你能把这个概念包围起来!

答案 1 :(得分:1)

一种方法是设置警告对话框的正面按钮。

将每个按钮单击警告对话框,如下所示:

    new AlertDialog.Builder(this)
            .setTitle("Problem")
            .setMessage(
                    "Please Check your *whatever is wrong* ")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    //Do the next activity

                    dialog.dismiss();
                }
            }).show();

如果你想要详细的代码,那么我会。干杯!

相关问题