Android之Notification、NotificationChannel、NotificationCompat.Builder弃用与更新

package com.example.notification;


import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    Button button1,button2;
    NotificationManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);
        manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //高版本需要渠道
                if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
                    //只在Android O之上需要渠道
                    NotificationChannel notificationChannel = new NotificationChannel("channelid1","channelname",NotificationManager.IMPORTANCE_HIGH);
                    //如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道,通知才能正常弹出
                    manager.createNotificationChannel(notificationChannel);
                }
                NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,"channelid1");
                builder.setSmallIcon(R.drawable.ico)
                        .setContentTitle("通知标题")
                        .setContentText("通知内容")
                        .setAutoCancel(true);
                manager.notify(0x12,builder.build());
            }
        });
    }
}

 

posted @ 2019-01-25 09:12  寅春树  阅读(9828)  评论(1编辑  收藏  举报