我正在尝试运行此脚本,但是在doInBackground()中的某个位置将其重新启动以启动活动。

(我想做的是扫描所有可用的SSID并在数据库中检查它们)

这是我的代码:

Button btnHit;
TextView txtJson;
private static final String  TAG = "My Activity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_find_connection);

    btnHit = (Button) findViewById(R.id.request);
    txtJson = (TextView) findViewById(R.id.results);


    if (Build.VERSION.SDK_INT > 22) {

        final String CoarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
        final String AccessWifi = Manifest.permission.ACCESS_WIFI_STATE;
        final String ChangeWifi = Manifest.permission.CHANGE_WIFI_STATE;

        if (checkSelfPermission(CoarseLocation) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
        }

        if (checkSelfPermission(AccessWifi) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE}, 123);
        }

        if (checkSelfPermission(ChangeWifi) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE}, 123);
        }
    }



    LocationManager lman = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    boolean network_enabled = false;

    try
    {
        network_enabled = lman.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {}


    if (!network_enabled)
    {
        startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
    }



    final WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

    mWifiManager.setWifiEnabled(true);

    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            List<ScanResult> results = mWifiManager.getScanResults();
            final int Amount = results.size();

            Log.v(TAG, "Wifi Scan Results Count: " + Amount);

            int num = 0;

            while (num < Amount)
            {
                Log.v(TAG, "SSID  =  " + results.get(num).SSID);

                num = num+1;
            }

            int dis = 0;

            String res = "Results:\n\n\n";

            while (dis < Amount)
            {
                res = res + results.get(dis).SSID + "\n\n";

                String surl = "http://myurl.com?ssid=" + results.get(dis).SSID;
                new JsonTask().execute(surl);

                dis = dis+1;
            }

            TextView textres = (TextView) findViewById(R. id. resnet);
            textres.setText(res);

        }
    }, filter);

    mWifiManager.startScan();

}



private class JsonTask extends AsyncTask<String, String, String> {

    ProgressDialog pd;

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(FindConnection.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {

                buffer.append(line+"\n");

                if (line != "null")
                {
                    Toast.makeText(getApplicationContext(), "Found one...", Toast.LENGTH_SHORT).show();
                }

                Log.d("Response: ", "> " + line);

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}


这是我得到的错误:

11-12 19:48:56.920 21711-21811/com.comhet.comhet E/AndroidRuntime:
FATAL EXCEPTION: AsyncTask #1
Process: com.comhet.comhet, PID: 21711
java.lang.RuntimeException: An error occurred while executing doInBackground()
   at android.os.AsyncTask$3.done(AsyncTask.java:309)
   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
   at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
   at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread
that has not called Looper.prepare()
   at android.os.Handler.<init>(Handler.java:200)
   at android.os.Handler.<init>(Handler.java:114)
   at android.widget.Toast$TN.<init>(Toast.java:362)
   at android.widget.Toast.<init>(Toast.java:109)
   at android.widget.Toast.makeText(Toast.java:276)
   at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:194)
   at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:156)
   at android.os.AsyncTask$2.call(AsyncTask.java:295)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
   at java.lang.Thread.run(Thread.java:818)

最佳答案

您试图在AsyncTask的doInBackground()方法中显示Toast。不允许这样做,因为doInBackground()方法在后台线程上运行,并且无法执行与UI线程相关的操作。

如果要检查返回的值,请记录返回的值,或在onPostExecute()方法中放入Toast。

关于java - 上课时应用进入MainActivity,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40565977/

10-11 19:05