Sobes.tech
Junior

როგორ შევქმნათ შეტყობინება Android-ში?

sobes.tech AI

პასუხი AI-სგან

Android-ში შეტყობინების შექმნა მოითხოვს შემდეგ ნაბიჯებს:

  1. შექმენით შეტყობინების არხი (API დონე 26 და ზევით).
  2. შექმენით შეტყობინება NotificationCompat.Builder-ის გამოყენებით.
  3. გამოიტანეთ შეტყობინება შეტყობინების მენეჯერის საშუალებით.
// შეტყობინების არხის შექმნა (API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "my_channel_id";
    CharSequence channelName = "My Channel";
    String channelDescription = "Description for My Channel";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
    channel.setDescription(channelDescription);
    // არხის რეგისტრაცია სისტემაში
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

// შეტყობინების შემქმნელი
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_channel_id") // არხის ID მიუთითეთ
        .setSmallIcon(R.drawable.ic_notification) // ხატული შეტყობინებისთვის
        .setContentTitle("შეტყობინების სათაური") // სათაური
        .setContentText("შეტყობინების ტექსტი") // ტექსტი
        .setPriority(NotificationCompat.PRIORITY_DEFAULT); // პრიორიტეტი

// PendingIntent შექმნა — მოქმედება დაჭერისას
// მაგალითად, აქტივობის გახსნა
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // API S+ ფლაგი
builder.setContentIntent(pendingIntent);

// შეტყობინების ჩვენება
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
int notificationId = 1; // უნიკალური ID
notificationManagerCompat.notify(notificationId, builder.build());

ძირითადი კომპონენტები:

  • პატარა ხატულა: setSmallIcon(), გამოჩნდება სტატუსის ზოლში
  • სათაური: setContentTitle(), მთავარი ტექსტი
  • ტექსტი: setContentText(), დამატებითი ტექსტი
  • შეტყობინების არხი (API 26+): ჯგუფი საერთო პარამეტრებით
  • PendingIntent: მოქმედება, რომელიც შესრულდება დაჭერისას

გარდა ამისა, შეგიძლიათ დაამატოთ დიდი სურათი (setStyle(new NotificationCompat.BigPictureStyle())), მოქმედების ღილაკები (addAction()), ხმა, ვიბრაცია და სხვა პარამეტრები.