2

I have a BluetoothSocket mmSocket; declared in public cass of my main activity.

In a function, i asign value a variable and if connected i start a Thread.

    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); 
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mmSocket.connect();
    mConnectedThread = new ConnectedThread(mmSocket);
    mConnectedThread.start();

My code runing ok.

But, when i start another activity in menu, if i return in less of 5 secs to main activity the thread is ok and mi app read from BT ok. But if i stay in activity B more of 10 secs when i return to the main activity the variable mmSocket is null and my thread is kill.

    Intent i = new Intent(getApplicationContext(), AjustesActivity.class);
    i.putExtra("distancia", Math.floor(MetrosRecorridos / 10));
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivityForResult(i, 3);

Any solution?

EDIT (14/07/2015)

In my service class i have:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

//In this part i connected whith Bluetooth.

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            byte[] buffer = new byte[2500];
            int bytes;
        while (true) {
        try {
            bytes = mmInStream.read(buffer); 
                        String readMessage = new String(buffer, 0, bytes);
                    sendMessage(readMessage);
        } catch (IOException e) { }
        }
    });
}

private void sendMessage(String Msg) {
  Intent intent = new Intent("custom-event-name");
  intent.putExtra("message", Msg);
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

and in my mainactivity:

@Override
public void onCreate(Bundle savedInstanceState) {
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
       new IntentFilter("custom-event-name"));
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra("message");
 }
};

When i debug the main acitivity no recived the message. any idea?

Thanks

  • Just remove `i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);` as its make one instance on the activity and its not working with `startActivityForResult` – Ali Helmy Jul 10 '15 at 23:41
  • How about using onSaveInstanceState (http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle, android.os.PersistableBundle) ) to save the variable that you need? Then, when the activity is recreated you can retrieve it again. However, If you need a thread that should persist, You can use a Service (http://developer.android.com/guide/components/services.html) – Eduardo Gamboa Ureña Jul 10 '15 at 23:41
  • How u assumed that your thread is killed? Threads are not bound to activity - you could lose only reference to it. Thread can be stopped only by call stop() method or by finish run() method. Pleas show your stack dump – ceph3us Jul 11 '15 at 07:35

1 Answers1

1

Put your code into the background service and start it in the separate thread. It won't be deleted until system will need free space.

If you have to share data from service to activity, you can create new interface and use callbacks or create local broadcast receiver and send intents with bundle.

Manifest:

<service
        android:name=".yourBluetoothService"
        android:exported="false"/>

Service file:

public class yourBluetoothService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        // init code
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.v("BluetoothService", "service started");

        new Handler().post(new Runnable() {
            @Override void run() {
                //your code to start service
            }      
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

EDIT (14/07/2015)

In my service class i have:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

//In this part i connected whith Bluetooth.

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            byte[] buffer = new byte[2500];
            int bytes;
        while (true) {
        try {
            bytes = mmInStream.read(buffer); 
                        String readMessage = new String(buffer, 0, bytes);
                    sendMessage(readMessage);
        } catch (IOException e) { }
        }
    });
}

private void sendMessage(String Msg) {
  Intent intent = new Intent("custom-event-name");
  intent.putExtra("message", Msg);
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

and in my mainactivity:

@Override
public void onCreate(Bundle savedInstanceState) {
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
       new IntentFilter("custom-event-name"));
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra("message");
 }
};

When i debug the main acitivity no recived the message. any idea?

Thanks

Anton Shkurenko
  • 4,301
  • 5
  • 29
  • 64
  • Thanks! I will try with this code... i have a question... When I make the connection with the bluettoth? Within the service on onCreate() ? Thanks – r_ameijeiras Jul 13 '15 at 11:00
  • @r_ameijeiras init it, add listeners, params in the onCreate(), start scan in the onStartCommand() – Anton Shkurenko Jul 13 '15 at 12:15
  • Ah! Ok! Add the code that connect in the onStartCommand and the code that read the data in run() of handler, no? THanks – r_ameijeiras Jul 13 '15 at 14:24
  • 1
    @r_ameijeiras check this answer for deeper unsertanding http://stackoverflow.com/questions/14182014/android-oncreate-or-onstartcommand-for-starting-service Seems like yes, you're right – Anton Shkurenko Jul 13 '15 at 14:33
  • Ok, the code is OK. But i dont know how update my textview of mainactivity with the data of BluetoothService. Any solution? – r_ameijeiras Jul 13 '15 at 15:05
  • @r_ameijeiras create local broadcast receiver in the your activity, send broadcast with a bundle of your data. Override onReceive method and change your textview there. Here is tutorial http://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager – Anton Shkurenko Jul 13 '15 at 15:11
  • Ok. I created a Broadcast Receiver but dont send the data to mainactivity because in a run of service i have a WHILE (TRUE) for recibe data of bluettoth. Any idea? – r_ameijeiras Jul 14 '15 at 09:58
  • Create listener and in that cycle you can create and send broadcast. If I don't understand you, share me code. Use codeshare or smth like that – Anton Shkurenko Jul 14 '15 at 10:28
  • @r_ameijeiras that was bad idea. In answer it has to be right code. Try to use not localbroadcast manager but global, or debug it with breakpoints – Anton Shkurenko Jul 14 '15 at 12:04
  • you can put a example of code complete?? Thnaks... :( – r_ameijeiras Jul 14 '15 at 13:13
  • @r_ameijeiras to be honest it's pretty hard to offer something, with only thoughts about your project. Share github link or I dont know – Anton Shkurenko Jul 14 '15 at 14:03