1

Hie all, i am working on Bluetooth connections and to do that i have device address and i want send it to a service which handle Bluetooth connections

i want to send string(device address) from activity to service (Android)

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

Code In SERVICE CLASS:

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


        }
Sujit
  • 10,512
  • 9
  • 40
  • 45
shilpa
  • 13
  • 1
  • 4

3 Answers3

3

According to this article i've implemented Activity that sends String to Service. You can look below, maybe it will help.

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

}
marioosh
  • 27,328
  • 49
  • 143
  • 192
0

Have you looked at the Service documentation and examples from and Android docs?

In a nutshell, you can use a Messenger to send meaningful messages to the service. Look at the section on: Remote Messenger Service Sample

Tanner Perrien
  • 3,133
  • 1
  • 28
  • 35
  • The documentation doesnt show how to send a String. In which not anything can be sent via Object Message.obj –  Feb 10 '20 at 03:10
-1

you cant send data directly from activity to service, you need to used Android Interface Definition Language (AIDL)

Using aidl you can call any method in service that define in .aidl file from activity, if you want to pass data than you can pass data as arguments of methods

for additional info see Implementing Remote Interface Using AIDL

Jignesh Dhua
  • 1,471
  • 1
  • 14
  • 31
  • 1
    AIDL is not the only way to communicate with a `Service`, and it is definitely not the easiest. – Tanner Perrien Jun 23 '11 at 13:30
  • This answer is incorrect, you can bind to a service to communicate, or you can send Intents. Take a look at the [Android Developers](http://developer.android.com/guide/topics/fundamentals/services.html#ExtendingIntentService) documentation. – David Snabel-Caunt Jun 23 '11 at 13:57
  • This answer is incorrect! really? Why is AIDL complicated??? I was just reading a bit of the documentation and it seems easy. Only issue seems to be thread handling. But as long as your aidl functions are thread safe then no problem. Making your apps thread safe is super easy. For one use non mutating variables as much as possible. Thanks for inspiring me to think aidl. Messenger is easy but cumbersome to make a my android debugging console. I am hoping aidl will be faster. And allow me to use a wider array of data types. I am even having trouble sending String via Messenger.send –  Feb 10 '20 at 03:55