Question

I'm trying to create an application that use a background service to connect to BluetoothDevice:

Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);


    /* ... Create Data Scruct ...*/
    dataStruct = new DataStruct();

    /* Start Service /*
    Intent intentService = new Intent(this,NewService.class);
    intentService.putExtra("Data", dataStruct);
    startService(intentService);


}

Service:

public class NewService extends Service{
@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      super.onStartCommand(intent, flags, startId); 
dataStruct = intent.getStringExtra("Data");
...
connectBluetooth(dataStruct.getDeviceBT());
return START_NOT_STICKY;
}

public void BTReceive(){
updateDataStruct();
}
}

Everytime BT is connected and receive something special a Notification Occur When click on Notification, Activity starts (by Intent) It works, but I'd like to start this application without start Activity layout. I'd like to start just service and start it at Startup of mobile. Last question, when I swipe out Application from "last application list" Service stops and bluetooth communication is lost. There is a way to avoid it? I'd like to kill Activity but stay alive service

Thank you

Was it helpful?

Solution

*) I'd like to start just service and start it at Startup of mobile.?

Answer: Use this code below to start service on startup.

<receiver
        android:name="com.xxx.CustomBroadcastReciever"
        android:enabled="true" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

Use Broadcast receiver to receive a intent on startup or on boot completed, then start your service from there.

*) when I swipe out Application from "last application list" Service stops and bluetooth communication is lost. There is a way to avoid it?

Answer: Use AlarmManager to avoid it. Use repeat alarm with runs very 5 - 10 seconds, from there you can call a BroadCastReceiver. So now the BroadCastReceiver is called very 5-10seconds. Check if the service is still running, else start it in BroadCastReceiver.

Intent intent = new Intent(this, CustomBroadcastReciever.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
            intent, PendingIntent.FLAG_CANCEL_CURRENT);

        // InexactRepeating allows Android to optimize the energy
        // consumption
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), (5 * 1000), pendingIntent);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top