javaandroidbluetoothbluetooth-lowenergyandroid-bluetooth

StartForeground_Service still does not work


I'm working on a Bluetooth Advertisement Program. It compiles in SDK 28. As required by the documentation I added the permission android.permission.FOREGROUND. But even now, if the button for BluetoothAdvertisements is clicked and startForeground() gets called the App crashes.

After i added the permission the catch is never reached. Before i added the permission i would still reach the catch sequence and the message told me, that I have to add the FOREGROUND_SERVICE permission as mentioned above.

For this App I'm using Java.

`/**
     * Starts BLE Advertising.
     */
    private void startAdvertising() {
        goForeground();

    Log.d(TAG, "Service: Starting Advertising");

    if (mAdvertiseCallback == null) {
        AdvertiseSettings settings = buildAdvertiseSettings();
        AdvertiseData data = buildAdvertiseData();
        mAdvertiseCallback = new SampleAdvertiseCallback();

        if (mBluetoothLeAdvertiser != null) {
            mBluetoothLeAdvertiser.startAdvertising(settings, data,
                    mAdvertiseCallback);
        }
    }
}

/**
 * Move service to the foreground, to avoid execution limits on background processes.
 *
 * Callers should call stopForeground(true) when background work is complete.
 */
private void goForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);
    Notification n = new Notification.Builder(this)
            .setContentTitle("Advertising device via Bluetooth")
            .setContentText("This device is discoverable to others nearby.")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();
    //TODO: startForeground throws Exception. Has to be Fixed
    try{
        startForeground(FOREGROUND_NOTIFICATION_ID, n);
    } catch (SecurityException e) {
        Toast toast = Toast.makeText(this, e.getMessage() + " Exception Throwed", Toast.LENGTH_SHORT);
        toast.getView().setBackgroundColor(Color.parseColor("#FF0FF0"));
        toast.show();
    }

}`

I was asked for Stack Trace, so here is it:

FATAL EXCEPTION: main Process: com.example.android.bluetoothadvertisements, PID: 9760 android.app.RemoteServiceException$CannotPostForegroundServiceNotificationException: Bad notification for startForeground at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:1983) at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2242) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7898) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)


Solution

  • Your code is outdated: Replace the two lines

    PendingIntent pendingIntent = ...
    Notification n = ...
    

    by

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
    NotificationChannel notificationChannel = new NotificationChannel("your_Channel_ID", "your channel name", NotificationManager.IMPORTANCE_LOW);
    getSystemService(NotificationManager.class).createNotificationChannel(notificationChannel);
    Notification n = new Notification.Builder(this, "your_Channel_ID")