Table des matières
Correct Answer
Maison Java StartForeground_Service ne fonctionne toujours pas

StartForeground_Service ne fonctionne toujours pas

Feb 08, 2024 pm 08:42 PM

Contenu de la question

Je développe un programme publicitaire Bluetooth. Il est compilé dans le SDK 28. Comme l'exige la documentation, j'ai ajouté l'autorisation android.permission.foreground. Mais même maintenant, si je clique sur le bouton « Bluetooth Advertise » et que j’appelle startforeground(), l’application plante.

Après avoir ajouté les autorisations, la capture n'a jamais été atteinte. J'arrive toujours à la séquence de capture avant d'ajouter les autorisations, et le message me dit que je dois ajouter les autorisations foreground_service mentionnées ci-dessus.

Pour cette application, j'utilise 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();
    }

}`
Copier après la connexion

On m'a demandé une trace de stack, la voici donc :

Exception fatale : majeure Processus : com.example.android.bluetoothadvertisements, pid : 9760 android.app.remoteserviceexception$cannotpostforegroundservicenotificationexception : notification d'erreur de startforeground sur android.app.activitythread.throwremoteserviceexception (activitythread.java:1983) sur android.app.activitythread.-$$nest$mthrowremoteServiceException (Source inconnue : 0) dans android.app.activitythread$h.handlemessage(activitythread.java:2242) sur android.os.handler.dispatchmessage(handler.java:106) sur android.os.looper.looponce(looper.java:201) sur android.os.looper.loop(looper.java:288) sur android.app.activitythread.main (activitythread.java:7898) sur java.lang.reflect.method.invoke (méthode native) sur com.android.internal.os.runtimeinit$methodandargscaller.run(runtimeinit.java:548) Dans com.android.internal.os.zygoteinit.main(zygoteinit.java:936)


Correct Answer


Votre code est obsolète : remplacez les deux lignes

pendingintent pendingintent = ...
notification n = ...
Copier après la connexion

Par

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")
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)