从活动向服务发送字符串(数据)(Android)

时间:2011-06-23 13:18:40

标签: android service bluetooth

全部, 我正在进行蓝牙连接,为此我有设备地址,我想将其发送到处理蓝牙连接的服务

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

ACTIVITY CLASS中的代码:

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);
        }


        }

3 个答案:

答案 0 :(得分:2)

根据这个article我实现了将String发送到服务的Activity。你可以看下面,也许它会有所帮助。

<强> 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();
    }    

}

答案 1 :(得分:0)

您是否查看了Service documentation和Android文档中的示例?

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

答案 2 :(得分:-1)

您无法直接从活动向服务发送数据, 你需要使用Android Interface Definition Language (AIDL)

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

有关其他信息,请参阅Implementing Remote Interface Using AIDL