Maison  >  Article  >  StartForeground_Service ne fonctionne toujours pas

StartForeground_Service ne fonctionne toujours pas

WBOY
WBOYavant
2024-02-08 20:42:23379parcourir
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();
    }

}`

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 = ...

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

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:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer