我在AsyncTask类中获得了设备的GPS协调(通过getLocation方法)但是,如果GPS被禁用,我打开一个对话框,用户可以转移到"设置"区域并转动GPS" on"或取消。每次打开对话框警报之前应用程序崩溃,然后用户甚至按下其中一个按钮。我该如何解决?
public class StarTask extends AsyncTask<Void,Void,ArrayList<Song>>{
final int k_ThreadSleepTime = 3000;
final int k_MaxThreadTries = 7;
double latitude = 0;
double longitude = 0;
GPSTracker gps;
TestMain client;
@Override
protected void onPreExecute() {
super.onPreExecute();
gps = new GPSTracker(getApplication());
}
@Override
protected ArrayList<Song> doInBackground(Void... params) {
ArrayList<Song> list = new ArrayList();
client = new TestMain();
int tries = 0;
String o;
getLocation();
String url = builtURL();
try {
String jsonPageStr = client.doGetRequest(url);
JSONObject obj = new JSONObject(jsonPageStr);
userId = obj.getJSONObject("info").getInt("user_id");
isWait = (wait.equals("true"));
while (isWait && tries < k_MaxThreadTries) {
url = builtURL();
jsonPageStr = client.doGetRequest(url);
obj = new JSONObject(jsonPageStr);
if (!(obj.equals("") || obj.equals(null))) {
isWait = (wait.equals("true"));
}
tries++;
try {
Thread.sleep(k_ThreadSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(tries == k_MaxThreadTries) {
//exit the App
onMyDestroy();
}
}
private String builtURL() {}
private void getLocation() {
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
//gps.showSettingsAlert();
showSettingsAlert();
}
gps.stopUsingGPS();
}
public void showSettingsAlert(){
runOnUiThread(new Runnable() {
@Override
public void run() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(intent);
hasBeenNoGps = true;
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
hasBeenNoGps = true;
onMyDestroy();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
@Override
protected void onPostExecute(ArrayList<Song> aVoid) {
super.onPostExecute(aVoid);
答案 0 :(得分:0)
您正在showSettingsAlert()
上执行用户操作,该操作在doInBackground()
的{{1}}期间调用。允许的方法是使涉及UI的所有操作远离AsyncTask
。在这里,您可以从doInBackground()
中移除else条件,而不是实现它getLocation()
。像这样,
onPreExecute()
答案 1 :(得分:0)
您正在尝试在后台线程(在AsyncTask内)中运行UI线程,您可以做的是在AsyncTask类中创建一个全局对话框并在 doInBackground 方法上显示它然后关闭它 onPostExecute()。您的对话框需要上下文。