Home  >  Article  >  StartForeground_Service still doesn't work

StartForeground_Service still doesn't work

WBOY
WBOYforward
2024-02-08 20:42:23457browse
Question content

I am developing a Bluetooth advertising program. It is compiled in sdk 28. As required by the documentation, I added the android.permission.foreground permission. But even now, if I click the "Bluetooth Advertise" button and call startforeground(), the app crashes.

After I added the permissions, the capture was never reached. I still get to the capture sequence before adding the permissions, and the message tells me that I have to add the foreground_service permissions mentioned above.

For this application I am 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 a stack trace, so here it is:

FATAL EXCEPTION: MAJOR Process: com.example.android.bluetoothadvertisements, pid: 9760 android.app.remoteserviceexception$cannotpostforegroundservicenotificationexception: error notification of startforeground at android.app.activitythread.throwremoteserviceexception(activitythread.java:1983) at android.app.activitythread.-$$nest$mthrowremoteServiceException (Unknown source: 0) in 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) In com.android.internal.os.zygoteinit.main(zygoteinit.java:936)


Correct answer


Your code is obsolete: replace both lines

pendingintent pendingintent = ...
notification n = ...

Depend on

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")

The above is the detailed content of StartForeground_Service still doesn't work. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete