Search code examples
androidassetswear-osillegalstateexception

IllegalStateException when calling blockingConnect in wear Service


I am trying to develop an Android wear app and pass an asset from the mobile helper activity. I have followed the official document for passing assets - Transferring Assets, but I am getting the following error when trying to load a bitmap from the asset passed in the onDataChanged function. Note that the code works when passing String values. The code is as follows:

public Bitmap loadBitmapFromAsset(Bitmap bitmap, Asset asset) {
    if (asset == null) {
        throw new IllegalArgumentException("Asset must be non-null");
    }

    ConnectionResult result = mGoogleApiClient.blockingConnect(5000, TimeUnit.MILLISECONDS);
    if (!result.isSuccess()) {
        return null;
    }

    InputStream assetInputStream = Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset).await().getInputStream();
    mGoogleApiClient.disconnect();

    if (assetInputStream == null) {
        return null;
    }

    if (bitmap != null) {
        bitmap.recycle();
        bitmap = null;
    }

    bitmap = BitmapFactory.decodeStream(assetInputStream);
    return bitmap;
}

The error I am getting is the following:

java.lang.IllegalStateException: blockingConnect must not be called on the UI thread at com.google.android.gms.common.internal.zzx.zza(Unknown Source) at com.google.android.gms.common.api.internal.zzj.blockingConnect(Unknown Source) ...

Any ideas on what is causing this?


Solution

  • The solution was finally to execute the loadBitmapFromAsset in a runnable. Don't see why I didn't figure this out earlier... I have not found a similar post so hopefully it will help someone.

    new Thread(new Runnable() {
        @Override
        public void run() {
        ...
        }
    }).start();