当我有异步调用时,为什么我的启动动画无法正常工作?

时间:2015-09-23 20:22:41

标签: android android-asynctask android-animation splash-screen

我有一个启动动画,我从onCreate开始,并在onStart中调用读取当前位置(Google Play服务)。但正因如此,我的动画根本没有开始。

知道为什么会这样吗?

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);
    setLogoAnimation();
}


 private void setLogoAnimation() {
    Animation blink =AnimationUtils.loadAnimation(this,R.anim.blink);
    imgLogo = (ImageView)findViewById(R.id.imgLogo);
    imgLogo.startAnimation(blink);
    imgLogo.setVisibility(View.VISIBLE);
}


 protected void onStart() {
    super.onStart();
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                imgLogo.setAnimation(null);
            }
        }
    });

    t.start();


    readLocation();
}

当我将这个调用注释掉readLocation()时,它完美无缺。

public void readLocation() {
    // Check if Google Play Services are available on device
    prefs  = PreferenceManager.getDefaultSharedPreferences(context);
    if (checkPlayServices())
    {
        // Build Google API Client
        buildGoogleApiClient();
        if (mGoogleApiClient !=null)
        {
            mGoogleApiClient.connect();
        }
    }

}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        }
        return false;
    }
    return true;
}

 @Override
public void onConnected(Bundle arg0) {
    // Once connected with google api, get the location
    getLatLong();
    getAddressFromLocation(latitude, longitude,
            context, new GeocoderHandler());

}

1 个答案:

答案 0 :(得分:0)

也许这篇文章可以提供帮助,它解释了在UI上运行的线程。 http://www.myandroidsolutions.com/2014/04/06/run-code-on-mainui-thread-on-android/ 从其他线程访问UI线程可能会导致问题。