[JAVA] Programming memorandum from 51 years old Notification IntentService Service code memorandum / summary

Notification code memo

https://akira-watson.com/android/service.html

Notice:
Regarding startForeground (id, notification), if id is 0, it crashes, if id is 1, notification function is disabled, id is 2 I encountered the phenomenon of being notified. Note that it was OK if it was not 0 in the street, but it was not so in my code, so it is set to 2 in the code

Notification.Builder(context,channelId) || NotificationCompat.Builder(context,channelId)The context is required to use the notification area by the Android System and will not exist beyond the lifetime of the generated Builder object.

** 1. Notification code before API25 ** ** 2. Notification code for API 26 or later ** ** 3. Android 9 Pie or later manifest additional code ** ** 4. Code that determines API 25 or earlier and API 26 or later **

1. Notification code before API25

--Content settings with builder --Display notification with notify

MainActivity


@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"channel_id");
   builder.setSmallIcon(R.drawable.notification_icon)
          .setContentTitle("title under 8")
          .setContentText("content under 8")
          .setPriority(NotificationCompat.PRIORITY_DEFAULT);

   NotificationManager manager =(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
   manager.notify(0,builder.build());
}

2. API26 or later notification code

--Content settings with builder --Set importance on channel --Generate channel --Display notification with notify

MainActivity


@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"channel_id");
   builder.setSmallIcon(R.drawable.notification_icon)
           .setContentTitle("title over 8")
           .setContentText("content over 8");

   int importance = NotificationManager.IMPORTANCE_DEFAULT;
   NotificationChannel channel = new NotificationChannel("channel_id","name",importance);

   NotificationManager manager =(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
   manager.createNotificationChannel(channel);
   manager.notify(0,builder.build());
}

3. Android 9 Pie or later manifest additional code

AandroidManifest


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

4. Code that determines API 25 or earlier and API 26 or later

if(Build.VERSION.SDK_INT >=26)

MainActivity


String CHANNEL_ID = "channel_id";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    createNotificationChannel();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID);
    builder.setSmallIcon(R.drawable.notification_icon)
           .setContentTitle("title")
           .setContentText("content")
           .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    NotificationManager manager =(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
    manager.notify(0,builder.build());
}

private void createNotificationChannel(){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"channel_name",importance);
        NotificationManager manager =(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }
}

IntentService and Notification

1. Create notification with API16

--Create a project with Android studio targeting API16 --Service uses Intent Service --Emulator Android4.1 JellyBean API16 output

** Intent Service code without API Level judgment ** ** Intent Service code with API Level judgment **

API16 startService code (MainActivity)

MainActivity



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(this,MyService.class);
    if(Build.VERSION_SDK_INT >= 26){
       startForegroundService(intent);
    }else{
       startService(intent);
    }
}

IntentService code without API Level judgment

IntentService


@Override
public int onStartCommand(Intent intent,int flag,int starId){
    Context context = getApplicationContext();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"id")
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("Title")
            .setPriority(NotificationCompat.PRIORITY_LOW);
    NotificationManagerCompat manager = NotificationManagerCompat.from(context);
    manager.notify(1,builder.build());
    function();
    return START_STICKY;
}

public void function(){
//What you want to do
}

IntentService code with API Level

IntentService


public MyIntentService() {
    super("MyIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"channel");
    builder.setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("sample_title")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build();

    if(Build.VERSION.SDK_INT >=26){
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("channel","name",importance);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(channel);
    }

    NotificationManagerCompat compatManager =NotificationManagerCompat.from(this);
    startForeground(1,builder.build());
    compatManager.notify(1,builder.build());
    function();

    return START_STICKY;
}

public void function(){
//What you want to do
}

2. Create notification with API29

--Create a project with Android studio targeting API29 --Service uses Intent Service --Emulator Android9.0 Pie API29 output
Emulator Even if it is output to Android 4.1, it was notified normally

API29 MainActivity code

MainActivity


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(this,MyIntentService.class);
    if(Build.VERSION.SDK_INT >= 26){
        startForegroundService(intent);
    }else{
        startService(intent);
    }
}

API29 IntentService code

IntentService


protected void onHandleIntent(Intent intent) {
    Notification notification;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"id");
    notification = builder.setSmallIcon(R.drawable.notification_icon)
                          .setContentTitle("title")
                          .setContentText("text")
                          .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                          .build();
    startForeground(2,notification);

    if(Build.VERSION.SDK_INT >= 26){
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("id","name",importance);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
    managerCompat.notify(1,notification);
    function();

    return START_STICKY;
}

public void function(){
//What you want to do
}

Service and Notification

AndroidManifest.java

AndroidManifest.java


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

MainActivity.java --For API26 and above, start the service with startForegroundService (intent). --For API26 or less, start service with startService (intent).

MainActivity.java


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Intent intent = new Intent(this,MyService.class);
    Button btn_start = findViewById(R.id.btn_start);
    Button btn_stop  = findViewById(R.id.btn_stop);

    btn_start.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            if(Build.VERSION.SDK_INT >=26){
               startForegroundService(intent);
            }else{
               startService(intent);
            }
        }
    });

    btn_stop.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            stopService(intent);
        }
    });
}

MyService.java

MyService.java


@Override 
public int onStartCommand(Intent intent,int flags,int startId){
   //Set notification content
   Notification notification;
   Intent intent_pending = new Intent(this,MainActivity.class);
   PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent_pending,0);
   NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"id");
   notification = builder.setSmallIcon(R.drawable.notification_icon)
       .setContentTitle("Title")
       .setContentText("Text")
       .setContentIntent(pendingIntent)
       .build();

   //API26 and above: startForeground(notificationId,notification)Notification display with
   //Generate a channel by setting the importance of the channel for each notification
   if(Build.VERSION.SDL_INT >= 26){
      int importance = NotificationManager.IMPORTANCE_LOW;
      NotificationChannel channel = new NotificationChannel("id","nama",importance);
      NotificationManager manager = getSystemService(NotificationManager.class);
      manager.createNotificationChannel(channel);
      startForeground(1,notification);
   }else{
      //Less than API26: Set importance for each component
      // notify(notificationId,notification)Notification display with
      NotificationManagerCompat managerCompat = NotificationCompat.from(this);
      notification = builder.setPriority(NotificationCompat.PRIORITY_LOW).build();
      managerCompat.notify(1,notification);
   }
   // ToDo
   Log.d("msg","Mesage");

   //
   return START_STICKY;
}

Recommended Posts