Table of Contents
Correct answer
Home Java StartForeground_Service still doesn't work

StartForeground_Service still doesn't work

Feb 08, 2024 pm 08:42 PM

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();
    }

}`
Copy after login

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 = ...
Copy after login

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")
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)