如何在onCreate中正确运行while循环?

时间:2015-08-28 21:22:57

标签: android progress-bar oncreate

我正在制作此应用,当用户首次打开应用时,我只想运行一个进度条,直到该应用获得用户的GPS位置。然后开始活动,这样他们就可以做些什么。但我不断收到错误。我想知道是否有人能真正帮助我吗?

public class MyActivity extends Activity implements View.OnClickListener {
    private ProgressBar pb = null;
    @InjectView(R.id.frame)
    private boolean testrun = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        while(!testRun)
        {
             setContentView(R.layout.ProgressBar);
             pb = (ProgressBar) findViewById(R.id.progressBar1);
             pb.setVisibility(View.VISIBLE);
             //Then I create an instance of AsyncTask and try to get GPS      
             //coordinates and set testRun to true. 

        }
        setContentView(R.layout.test);
        ButterKnife.inject(this);



    }

所以我一直在崩溃,它甚至没有加载进度条布局......

2 个答案:

答案 0 :(得分:2)

您不应该阻止UI线程,因为用户将无法再与您的应用进行交互。而不是while循环,你应该显示一个等待指标。例如,您可以show a spinning wheel并在获得GPS位置后立即将其解除。

  

当您的应用执行密集型工作以响应用户交互时,除非您正确实施应用程序,否则此单线程模型可能会产生较差的性能。具体来说,如果UI线程中发生了所有事情,则执行网络访问或数据库查询等长时间操作将阻止整个UI。线程被阻止时,不会调度任何事件,包括绘制事件。从用户的角度来看,应用程序似乎挂起。更糟糕的是,如果UI线程被阻止超过几秒钟(当前大约5秒),则向用户呈现臭名昭着的“应用程序无响应”(ANR)对话框。然后,用户可能会决定退出您的应用程序,如果他们不满意,请将其卸载。

来源:http://developer.android.com/guide/components/processes-and-threads.html

修改
LocationListener使用回调。没有必要将它放在AsyncTask中。只需显示某种等待指标,只要调用onLocationChanged,就可以忽略等待指标。

答案 1 :(得分:1)

您在上面的代码段中不需要while循环。这应该给你一个想法:

首先查看设备上是否启用了GPS,否则提示用户这样做。

import android.location.LocationManager;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            showGPSDisabledAlertToUser(); // Write your own code for this 
        }

获取纬度和经度(双值):

LocationResult locationResult = new LocationResult(){
            @Override
            public void gotLocation(Location location){
                //Got the location!
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                 new sendRequest().execute();
                Log.i("","ALL" + latitude + ":" + longitude);
            }
        };
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(MainActivity.this, locationResult);

MyLocation.java文件

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 60000 * 15);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {

        }
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

您需要修改MyLocation文件以根据需要删除冗余,但这应该为您提供一般的想法。

另外,一旦在show()

中执行完毕,确保整个事情都在AsyncTask和preexecute() dismiss()postexecute()中的ProgressDialog中

希望这有帮助。