【问题标题】:sending string(data) from activity to service (Android)将字符串(数据)从活动发送到服务(Android)
【发布时间】:2011-06-23 13:18:39
【问题描述】:

大家好, 我正在处理蓝牙连接,为此我有设备地址,我想将其发送到处理蓝牙连接的服务

我想将字符串(设备地址)从活动发送到服务(Android)

活动类中的代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
               address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                startService(new Intent(CallBluetooth .this,BluetoothService.class));

                Intent myIntent = new Intent(CallBluetooth.this, BluetoothService.class);

                Bundle bundle = new Bundle();
            CharSequence data1 = "abc";
                bundle.putCharSequence("extraData",data1);
                myIntent.putExtras(bundle);

                PendingIntent  pendingIntent = PendingIntent.getService(CallBluetooth.this, 0, myIntent, 0);

               /*BluetoothService s = new BluetoothService();
               s.deviceAddress(address);*/
                // Attempt to connect to the device
               // mChatService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                openOptionsMenu();

            } else {
                // User did not enable Bluetooth or an error occured

                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }

服务类中的代码:

public void onStart(Intent intent, int startId) {
         // TODO Auto-generated method stub
         super.onStart(intent, startId);

         Bundle bundle = intent.getExtras();
         System.out.println("*******************"+"InsideOnStart");
        if(bundle != null)
        { 
            CharSequence data = (String) bundle.getCharSequence("extraData");
            System.out.println("*******************"+data);
        }


        }

【问题讨论】:

    标签: android service bluetooth


    【解决方案1】:

    根据这个article,我实现了将字符串发送到服务的活动。你可以看看下面,也许会有所帮助。

    MainActivity.java

    package com.example.androidtranslator;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.os.Message;
    import android.os.Messenger;
    import android.os.RemoteException;
    import android.view.Menu;
    import android.view.View;
    
    public class MainActivity extends Activity {
    
        private Messenger mService = null;
        private boolean mBound;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // some gui code etc...
    
            /**
            * Connect to an application service, creating it if needed
            */
            bindService(new Intent(this, TranslatorService.class), mConnection,
                    Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
        }
    
        /**
         * on some GUI action (click button) send message
         * 
         * @param view
         */
        public void translate(View view) {
            if (!mBound)
                return;
            Message msg = Message.obtain(null, TranslatorService.MSG_STRING,
                    "Some message (it can be from textView for example)");
            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        private ServiceConnection mConnection = new ServiceConnection() {
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mService = null;
                mBound = false;
            }
    
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mService = new Messenger(service);
                mBound = true;
            }
        };
    
    }
    

    TranslatorService.java

    package com.example.androidtranslator;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.os.Messenger;
    import android.widget.Toast;
    
    public class TranslatorService extends Service {
    
        public static final int MSG_STRING = 0;
    
        /**
         * Handler of incoming messages from clients.
         * Show Toast with received string
         */
        class IncomingHandler extends Handler {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_STRING:
                        Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        super.handleMessage(msg);
                }
            }
        }
    
        /**
         * Target we publish for clients to send messages to IncomingHandler.
         */
        final Messenger mMessenger = new Messenger(new IncomingHandler());
    
        /**
         * When binding to the service, we return an interface to our messenger
         * for sending messages to the service.
         */
        @Override
        public IBinder onBind(Intent intent) {
            Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
            return mMessenger.getBinder();
        }    
    
    }
    

    【讨论】:

      【解决方案2】:

      您是否查看过 Service documentation 以及 Android 文档中的示例?

      简而言之,您可以使用Messenger 向服务发送有意义的消息。请看以下部分:Remote Messenger Service Sample

      【讨论】:

      • 文档没有显示如何发送字符串。其中不能通过 Object Message.obj 发送任何东西
      【解决方案3】:

      您不能将数据直接从活动发送到服务, 你需要使用Android Interface Definition Language (AIDL)

      使用aidl,您可以从活动调用.aidl 文件中定义的服务中的任何方法,如果您想传递数据而不是将数据作为方法的参数传递

      更多信息请参阅Implementing Remote Interface Using AIDL

      【讨论】:

      • AIDL 不是与Service 沟通的唯一方式,也绝对不是最简单的。
      • 这个答案不正确,可以绑定一个服务进行通信,也可以发送Intents。查看Android Developers 文档。
      • 这个答案不正确!真的吗?为什么AIDL复杂???我只是在阅读一些文档,这似乎很容易。唯一的问题似乎是线程处理。但只要您的aidl 函数是线程安全的,那么就没有问题。使您的应用程序线程安全非常容易。一方面,尽可能多地使用非变异变量。感谢您启发我思考aidl。 Messenger 制作我的 android 调试控制台很容易但很麻烦。我希望aidl会更快。并允许我使用更广泛的数据类型。我什至无法通过 Messenger.send 发送字符串
      猜你喜欢
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2013-07-28
      • 2021-06-26
      相关资源
      最近更新 更多