当前位置: 首页 > 面试题库 >

无法将资产发送到Android Wear设备

傅越
2023-03-14
问题内容

我正在尝试将资产发送到我的Sony
SmartWatch3。我遵循了Google的文档(https://developer.android.com/training/wearables/data-
layer/assets.html
),但是它不起作用。

我的掌上电脑活动的代码:

public class MainActivityHandheld extends ActionBarActivity
{
    private GoogleApiClient mGoogleApiClient;
    private static final String MY_KEY = "com.example.andy.key.mykey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity_handheld);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendDataToWearable();
            }
        });

        Log.i("ANDY", "mGoogleApiClient before creation -- Handheld");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    Log.d("tag", "onConnected: " + connectionHint);
                    // Now you can use the Data Layer API
                }

                @Override
                public void onConnectionSuspended(int cause) {
                    Log.d("tag", "onConnectionSuspended: " + cause);
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    Log.d("tag", "onConnectionFailed: " + result);
                }
            })
            // Request access only to the Wearable API
            .addApi(Wearable.API)
            .build();
        Log.i("ANDY", "mGoogleApiClient after creation -- Handheld");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("ANDY", "mGoogleApiClient before connect -- Handheld");
        mGoogleApiClient.connect();
        Log.i("ANDY", "mGoogleApiClient after connect -- Handheld");
    }

    @Override
    protected void onStop() {
        Log.i("ANDY", "mGoogleApiClient before disconnect -- Handheld");
        mGoogleApiClient.disconnect();
        Log.i("ANDY", "mGoogleApiClient after disconnect -- Handheld");
        super.onStop();
    }

    private void sendDataToWearable()
    {
        try 
        {
            Log.i("ANDY", "Before send -- Handheld");
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            Asset asset = createAssetFromBitmap(bitmap);
            PutDataRequest request = PutDataRequest.create("/image");
            request.putAsset("profileImage", asset);
            Wearable.DataApi.putDataItem(mGoogleApiClient, request);
            Log.i("ANDY", "After send -- Handheld");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            Log.i("ANDY", "Exception -- Handheld : " + ex.getStackTrace().toString());
        }
    }

    private static Asset createAssetFromBitmap(Bitmap bitmap) {
        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
        return Asset.createFromBytes(byteStream.toByteArray());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main_activity_handheld, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

我的可穿戴活动的代码:

public class MainActivityWear extends Activity implements
    DataApi.DataListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private TextView mTextView;
private GoogleApiClient mGoogleApiClient;
private static final String MY_KEY = "com.example.andy.key.mykey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_wear);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            mTextView = (TextView) stub.findViewById(R.id.text);
        }
    });

    Log.i("ANDY", "mGoogleApiClient before creation -- Wearable");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            // Request access only to the Wearable API
            .addApi(Wearable.API)
            .build();
    Log.i("ANDY", "mGoogleApiClient after creation -- Wearable");
}

@Override
protected void onResume() {
    super.onResume();
    Log.i("ANDY", "mGoogleApiClient after connect (OnResume) -- Wearable");
    mGoogleApiClient.connect();
    Log.i("ANDY", "mGoogleApiClient after connect (OnResume) -- Wearable");
}

@Override
protected void onPause() {
    super.onPause();
    Log.i("ANDY", "mGoogleApiClient before removeListener & disconnect -- Wearable");
    Wearable.DataApi.removeListener(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
    Log.i("ANDY", "mGoogleApiClient after removeListener & disconnect -- Wearable");
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i("ANDY", "mGoogleApiClient before addListener -- Wearable");
    Wearable.DataApi.addListener(mGoogleApiClient, this);
    Log.i("ANDY", "mGoogleApiClient after addListener -- Wearable");
    // Now you can use the Data Layer API
}

@Override
public void onConnectionSuspended(int cause) {
    Log.d("tag", "onConnectionSuspended: " + cause);
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.d("tag", "onConnectionFailed: " + result);
}

@Override
public void onDataChanged(DataEventBuffer dataEvents) {

    Log.i("ANDY", "onDataChanged before boucle event -- Wearable");

    for (DataEvent event : dataEvents)
    {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            // DataItem changed
            DataItem item = event.getDataItem();
            if (item.getUri().getPath().compareTo("/image") == 0)
            {
                Log.i("ANDY", "onDataChanged before get Asset -- Wearable");
                DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                Asset profileAsset = dataMapItem.getDataMap().getAsset("profileImage");
                Bitmap bitmap = loadBitmapFromAsset(profileAsset);
                // Do something with the bitmap

                Log.i("ANDY", "onDataChanged after get Asset -- Wearable");

                try
                {
                    Log.i("ANDY", "onDataChanged before deserialize -- Wearable");
                    ArrayList<MyObject> myObjectArrayList = (ArrayList<MyObject>) Serializer.deserialize(array);
                    Log.i("ANDY", "onDataChanged after deserialize -- Wearable");
                }
                catch (Exception e) {
                    e.printStackTrace();
                    Log.i("ANDY", "onDataChanged exception -- Wearable :" + e.getStackTrace().toString());
                }
            }
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            // DataItem deleted
        }
    }
}

public Bitmap loadBitmapFromAsset(Asset asset) {
    if (asset == null) {
        throw new IllegalArgumentException("Asset must be non-null");
    }
    ConnectionResult result =
           mGoogleApiClient.blockingConnect(100, TimeUnit.MILLISECONDS);
    if (!result.isSuccess()) {
        return null;
    }
    // convert asset into a file descriptor and block until it's ready
    InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
            mGoogleApiClient, asset).await().getInputStream();
            mGoogleApiClient.disconnect();

    if (assetInputStream == null) {
        Log.w(TAG, "Requested an unknown Asset.");
        return null;
    }
    // decode the stream into a bitmap
    return BitmapFactory.decodeStream(assetInputStream);
}
}

手持式代码的执行工作正常(正确显示了日志),但是该程序未输入 onDataChanged
的可穿戴方法。但是,当我尝试发送整数而不是资产时,它可以正常工作:

PutDataRequest request = PutDataRequest.create("/array");
request.putInt("array", 90);
Wearable.DataApi.putDataItem(mGoogleApiClient, request);

有任何想法吗?我不明白发生了什么。


问题答案:

这很棘手,但是为了被调用,数据的内容必须更改。尝试将时间戳添加到DataMap。例如

PutDataMapRequest request = PutDataMapRequest.create("/image");
Asset asset = createAssetFromBitmap(bitmap);
request.putAsset("profileImage", asset);
DataMap dataMap = request.getDataMap(); 
dataMap.putLong("timestamp", System.currentTimeMillis());
PutDataRequest dataRequest = request.asPutDataRequest();      
Wearable.DataApi.putDataItem(mGoogleApiClient, dataRequest);


 类似资料:
  • 我有这个发邮件的密码 此代码为除之外的任何邮件提供商发送邮件。 这可能是什么原因

  • 我开始构建一些非常简单的应用程序,我想我已经掌握了如何在android Studio中创建基础知识。我一辈子都搞不清楚的是为什么我不能把数据发送到我的firebase实时数据库。 这是一个非常简单的应用程序,我试图让它目前的工作(因为我不能在更丰富的一个)--只需要一个按钮,应该发送“你好,世界!”

  • 问题内容: 我试图将字符串消息发送到在weblogic服务器中创建的JMS队列中。我使用Eclipse IDE,当我运行Web应用程序时,出现以下错误,tomcat服务器关闭。错误是 请帮助我。谢谢和最诚挚的问候 问题答案: 基于对该问题的一些快速研究,它似乎是由于在应用服务器和客户端之间使用不同的JDK级别引起的。我看到的大多数示例都表明,在Java 5上运行Weblogic时在客户端上使用Ja

  • 问题内容: 将标头发送到客户端后,无法设置标头。这是请求验证后的后端错误,看起来像标头问题。我为我的项目脏代码感到抱歉,我还需要做其他事情,因此在注释中有一些代码。这是我的代码 您可以在我的代码中发现其他错误,因为我尝试了许多不同的方法。这是passport.js配置文件 这是身份验证的ajax请求 非常感谢你。 问题答案: 这是由于您的代码试图从authenticate函数发送多个响应。 删除其

  • 将标头发送到客户端后,无法对其进行设置。这是我的身份验证post请求后的后端错误。看起来标题有问题。我很抱歉我的项目肮脏的代码,我需要做一些别的事情,所以有一些代码在评论中。这是我的代码 你可以在我的代码中找到其他错误,因为我尝试了许多不同的方法。以下是passport.js配置文件 这是用于身份验证的 ajax 请求 非常感谢。

  • 我知道我将文本文件放在了assets\chat1的位置。txt,我的代码也可以与其他txt一起使用,但不知何故,我总是遇到以下错误: 发生异常。 错误(无法加载资产:assets/chat1.txt) 我的代码: pubspec.yaml