当 运行 class 时应用进入 MainActivity
App goes to MainActivity when running class
我正在尝试 运行 这个脚本,但是在 doInBackground() 的某处它被重新启动 activity。
(我想做的是扫描所有可用的 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.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.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.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor.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)
") 原因:java.lang.RuntimeException:无法在未调用 Looper.prepare()"
的线程内创建处理程序
您不能在未调用 Looper.prepare 的线程上创建处理程序。主线程需要你。如果你想post到主线程,你需要在主线程上创建than handler。
您正试图在 AsyncTask 的 doInBackground() 方法中显示 Toast。这是不允许的,因为 doInBackground() 方法在后台线程上运行,无法执行与 UI 线程相关的操作。
如果要查看返回值,记录返回值或者在onPostExecute()方法中做Toast。
看看你的 doInBackground 方法
您不能在 doInBackground.It 中执行 UI 相关操作,应在 onPostExecute{} 方法中完成。
从 doInBackground 中删除:
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);
}
}
我正在尝试 运行 这个脚本,但是在 doInBackground() 的某处它被重新启动 activity。
(我想做的是扫描所有可用的 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.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.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.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor.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)
") 原因:java.lang.RuntimeException:无法在未调用 Looper.prepare()"
的线程内创建处理程序您不能在未调用 Looper.prepare 的线程上创建处理程序。主线程需要你。如果你想post到主线程,你需要在主线程上创建than handler。
您正试图在 AsyncTask 的 doInBackground() 方法中显示 Toast。这是不允许的,因为 doInBackground() 方法在后台线程上运行,无法执行与 UI 线程相关的操作。
如果要查看返回值,记录返回值或者在onPostExecute()方法中做Toast。
看看你的 doInBackground 方法
您不能在 doInBackground.It 中执行 UI 相关操作,应在 onPostExecute{} 方法中完成。
从 doInBackground 中删除:
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);
}
}