1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

51歳からのプログラミング 備忘 Notification IntentService Service コード備忘・まとめ

Last updated at Posted at 2019-08-23

Notification コード備忘

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

Notice:
startForeground(id,notification)に関して、idが0だとクラッシュ、idが1だと通知機能が無効となる、idが2とかなら通知される、という現象に出会った。巷では0でなければOKとなっていたけれど、僕のコードではそうならなかったので、コードでは2としてます、という注記

Notification.Builder(context,channelId) || NotificationCompat.Builder(context,channelId) のcontextは、AndroidSystemによって通知領域を利用するために必要で、生成されるBuilderオブジェクトの存在期間を超えて存在することはない

1.API25以前のnotificationコード
2.API26以降のnotificationコード
3.Android9 Pie以降のmanifest追加コード
4.API25以前とAPI26以降を判定するコード

1.API25以前のnotificationコード

  • builderでコンテンツ設定
  • 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以降のnotificationコード

  • builderでコンテンツ設定
  • channelに重要度を設定
  • channelを生成
  • 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.Android9 Pie以降のmanifest追加コード

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

4.API25以前とAPI26以降を判定するコード

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とNotification

1. API16でnotificationを作成

  • Android studio targeting API16 でプロジェクト作成
  • ServiceはIntentServiceを利用
  • Emulator Android4.1 JellyBean API16で出力

API Level判定なしのIntentServiceコード
API Level判定ありのIntentServiceコード

API16のstartServiceコード(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);
    }
}

API Level判定なしのIntentServiceコード

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(){
// やりたい処理
}

API LevelありのIntentServiceコード

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(){
// やりたい処理
}

2. API29でnotificationを作成

  • Android studio targeting API29 でプロジェクト作成
  • ServiceはIntentServiceを利用
  • Emulator Android9.0 Pie API29で出力

    Emulator Android4.1に出力しても正常に通知された

API29のMainActivityのコード

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のコード

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(){
// やりたい処理
}

ServiceとNotification

AndroidManifest.java
AndroidManifest.java
<manifest ...
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
MainActivity.java
  • API26以上は、startForegroundService(intent)でサービス開始。
  • API26未満は、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){
   // 通知コンテンツを設定
   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以上:startForeground(notificationId,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{
      // API26未満:コンポーネント毎に重要度を設定して
      // notify(notificationId,notification)で通知表示
      NotificationManagerCompat managerCompat = NotificationCompat.from(this);
      notification = builder.setPriority(NotificationCompat.PRIORITY_LOW).build();
      managerCompat.notify(1,notification);
   }
   // ToDo
   Log.d("msg","Mesage");

   //
   return START_STICKY;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?