How to keep bluetooth connection in background?

I am writing a bluetooth application communicating with a bluetooth module. It actually works very well. But I want the connection to remain established while the application is in the background, and other applications are used, so another action, such as incoming sms or something else, can trigger my application in the background to send messages to my device.

So far I am very confused how to do this. Can anyone give me some advice?

I also checked this: Bluetooth Reference Application - Threading? but it doesnโ€™t help me.

Here is my code: http://pastebin.com/C7Uynuan

Lateral information: there is a connection button that establishes a connection, and then there are 3 more buttons that send different messages to my device. In OnResume, I reconnect to my device, but this is not necessary if there is a stable connection.

Thank,

progNewfag

EDIT: Now I'm sure I need to use IntentService, but not sure how to do this.

+4
source share
1 answer

You need to study the service first

Here is an example service

Create a new class and name it for Exmaple: MyService

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
    public MyService() {
    }

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

    @Override
    public void onCreate() {
        Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onStart(Intent intent, int startId) {
        // For time consuming an long tasks you can launch a new thread here...
        // Do your Bluetooth Work Here
        Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onDestroy() {
            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

        }
    }

Now in your main action you can start the service through this code

 startService(new Intent(this, MyService.class));

To stop the service, put this code in MainActivity

stopService(new Intent(this, MyService.class));

See this post

.

http://www.javacodegeeks.com/2014/01/android-service-tutorial.html

http://examples.javacodegeeks.com/android/core/service/android-service-example/

EDIT:

: Activity Messaging

http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/

+4

All Articles