Implémentation des Menus Options et des Notifications dans Android

Les OptionsMenu dans Android offrent une méthode standard pour intégrer des menus contextuels. Historiquement, les appareils mobiles disposaient d'une touche physique MENU pour accéder à ces menus. Ce guide explique comment personnaliser le système de menus Endroid.

Pour un Activity, au-delà de la méthode onCreate(), il est nécessaire d'implémenter onCreateOptionsMenu() et onOptionsItemSelected() afin de gérer la création et la sélection des éléments du menu.

public class PrimaryActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.main_layout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu targetMenu) {
        targetMenu.add(0, 100, 0, "Partager");
        targetMenu.add(0, 101, 1, "À propos");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem selectedItem) {
        switch (selectedItem.getItemId()) {
        case 100:
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Partage");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, "Contenu à partager...");
            startActivity(Intent.createChooser(sharingIntent, getTitle()));
            break;
        case 101:
            Toast.makeText(PrimaryActivity.this, "Bonne journée !", Toast.LENGTH_SHORT).show();
            break;
        default:
            break;
        }
        return true;
    }
}

Le système de notifications Android utilise le NotificationManager pour gérer les alertes. Chaque notification possède un identifiant unique pour permettre les mises à jour.

Notification avec style par défaut L'exemple suivant configure une notification avec son, vibration et action au clic. Aucun fichier de layout n'est requis pour cette méthode de base.

public class AlertActivity extends Activity {

    private static final int NOTIFICATION_ID = 101;
    private int notificationCounter;

    private final String alertTicker = "Nouvelle alerte reçue";
    private final String alertTitle = "Bienvenue";
    private final String alertBody = "Découvrez nos nouvelles fonctionnalités.";

    private Intent targetIntent;
    private PendingIntent pendingAction;
    private Uri soundPath = Uri.parse("android.resource://com.example.notifications/" + R.raw.alert_sound);
    private long[] vibrationPattern = { 0, 150, 150, 250 };

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.alert_layout);

        targetIntent = new Intent(AlertActivity.this, DetailActivity.class);
        pendingAction = PendingIntent.getActivity(AlertActivity.this, 0, targetIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        Button triggerButton = findViewById(R.id.alert_trigger);
        triggerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notificationCounter++;
                Notification.Builder builder = new Notification.Builder(AlertActivity.this)
                    .setTicker(alertTicker)
                    .setSmallIcon(android.R.drawable.ic_dialog_info)
                    .setAutoCancel(true)
                    .setContentTitle(alertTitle)
                    .setContentText(alertBody + " (Total: " + notificationCounter + ")")
                    .setContentIntent(pendingAction)
                    .setSound(soundPath)
                    .setVibrate(vibrationPattern);

                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(NOTIFICATION_ID, builder.build());
            }
        });
    }
}

Notification avec vue personnalisée Pour une notification personnalisée, un layout spécifique est défini. Cela permet un contrôle accru sur l'apparence.

Exemple de fichier de layout (custom_alert.xml) :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_alert_root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#55000000"
    android:orientation="horizontal"
    android:padding="8dp">

    <ImageView
        android:id="@+id/alert_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_notification" />

    <TextView
        android:id="@+id/alert_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:textColor="#FFFFFF"
        android:textSize="12sp" />

</LinearLayout>

Intégration dans l'Activity :

public class CustomAlertActivity extends Activity {

    private static final int CUSTOM_NOTIFICATION_ID = 102;
    private int alertCount;
    private RemoteViews contentView;

    private final String tickerMessage = "Notification spéciale";
    private final String titleText = "Personnalisée";
    private final String bodyText = "Interface adaptée pour plus de clarté.";

    private Intent launchIntent;
    private PendingIntent clickAction;
    private Uri alertSound = Uri.parse("android.resource://com.example.notifications/" + R.raw.alert_sound);
    private long[] vibPattern = { 0, 200, 100, 200 };

    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.alert_layout);

        contentView = new RemoteViews(getPackageName(), R.layout.custom_alert);

        launchIntent = new Intent(CustomAlertActivity.this, DetailActivity.class);
        clickAction = PendingIntent.getActivity(CustomAlertActivity.this, 0, launchIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        Button customButton = findViewById(R.id.alert_trigger);
        customButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertCount++;
                contentView.setTextViewText(R.id.alert_message, bodyText + " (Total: " + alertCount + ")");

                Notification.Builder builder = new Notification.Builder(CustomAlertActivity.this)
                    .setTicker(tickerMessage)
                    .setSmallIcon(android.R.drawable.ic_dialog_alert)
                    .setAutoCancel(true)
                    .setContent(contentView)
                    .setContentIntent(clickAction)
                    .setSound(alertSound)
                    .setVibrate(vibPattern);

                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(CUSTOM_NOTIFICATION_ID, builder.build());
            }
        });
    }
}

Pour activer la vibration, il faut déclarer la permission dans le fichier AndroidManifest.xml :

<uses-permission android:name="android.permission.VIBRATE" />

Étiquettes: Android OptionsMenu Notification NotificationManager RemoteViews

Publié le 26 juillet à 01h50