android8.0以上版本的前台服务(通知)

1.申请权限

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

 

2.更改myService

public class MyService extend Service{

  private static final String TAG="MyService";

  private static final String ID="channel_1";

  private static final String NAME="前台服务";

  。。。

  public void onCreate(){

    super.onCreate();  

    Log.d("MyService","onCreate executed");

    if(Build.VERSION.SDK_INT >= 26){

      setForeground();

    }

  }

  private void setForeground(){

    NotificationManager manager=(NotificationManager)getSystemService (NOTIFICATION_SERVICE);

    NotificationChannel channel=new NotificationChannel (ID,NAME,NotificationManager.IMPORTANCE_HIGH);

    manager.createNotificationChannel (channel);

    Notification notification=new Notification.Builder (this,ID)

      .setContentTitle ("收到一条重要通知")

      .setContentText ("这是重要通知")

      .setSmallIcon (R.mipmap.ic_launcher)

      .setLargeIcon (BitmapFactory.decodeResource (getResources (),R.mipmap.ic_launcher))

      .build ();

    startForeground (1,notification);

  }

}

 

转载自:https://blog.csdn.net/julicliy/article/details/104313756

posted @ 2020-11-17 10:57  sun锦  阅读(576)  评论(0)    收藏  举报