可以在Android中添加服务作为监听器吗?

时间:2016-06-02 11:10:19

标签: android wear-os

我正在创建一个Android应用程序,我在后台启动一个服务,它应该作为Datachanged.BackgroundService的监听器当前没有做任何事情,除了在OnDatachanged中显示日志。我想做这样的事情

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent =new Intent(this,BackgroundService.class);
    startService(intent);
    Button button=(Button)findViewById(R.id.button);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    Log.d("Inside", "onConnected: " + connectionHint);
                    Toast.makeText(getApplicationContext(),"Inside On connected",Toast.LENGTH_SHORT).show();

                }
                @Override
                public void onConnectionSuspended(int cause) {
                    Log.d("Inside", "onConnectionSuspended: " + cause);
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    Log.d("Inside", "onConnectionFailed: " + result);
                }
            })
            // Request access only to the Wearable API
            .addApiIfAvailable(Wearable.API)
            .build();
    mGoogleApiClient.connect();
    // This is what I want to achieve.Is there any way around for this?
    Wearable.DataApi.addListener(mGoogleApiClient, BackgroundService.class);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
}

后台服务扩展了intentService和Implements Data.ApiDataListener。

1 个答案:

答案 0 :(得分:0)

如果您继承WearableListenerService,则在API中更改匹配数据时,系统将调用它。除非明确说明您要执行的操作,否则您不需要像addListener那样拨打Activity

我建议您从其中一个示例应用开始(https://developer.android.com/samples/DataLayer似乎是一个不错的选择)并从那里开始构建。 API确实有效。