Android 通知栏的用法

1、Android Studio中创建项目,在app/build.gradle中设置 targetSdkVersion,保证在26以上,保证Android版本处于8.0以上。当Android版本处于8.0以下无法进行通知渠道的设置,此为Android8.0的一个更新。

app/build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.bo.baisibudeqijietest"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.android.support:design:28.0.0'
}

在MainActivity:中设置通知并与8.0以下进行对比
/**
 * @author lk
 */
public class MainActivity extends AppCompatActivity {
    private Button btnChat;
    private Button btnSubscribe;
    private Boolean mIsSupportedBade;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnChat = findViewById(R.id.send_chat);
        btnSubscribe = findViewById(R.id.send_subscribe);
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
           String channelId = "chat";
           String channelName = "聊天消息";
           int importance  = NotificationManager.IMPORTANCE_HIGH;
           createNotificationChannel(channelId,channelName,importance);
           channelId = "subscribe";
           channelName = "订阅消息";
           importance = NotificationManager.IMPORTANCE_DEFAULT;
           createNotificationChannel(channelId,channelName,importance);
           btnChat.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   sendChat(btnChat);
               }
           });

           btnSubscribe.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   sendSubscribeMsg(btnSubscribe);
               }
           });

       }



    }
/**
 * 创建通知渠道
 * @param channelId
 * @param channelName
 * @param importance
 */
    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId,channelName,importance);
        channel.setShowBadge(true);
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
    public void sendChat(View view){
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = manager.getNotificationChannel("chat");
            if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE){
                Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE,getPackageName());
                intent.putExtra(Settings.EXTRA_CHANNEL_ID,channel.getId());
                startActivity(intent);
                Toast.makeText(this, "请手动将通知打开", Toast.LENGTH_SHORT).show();
            }
        }
        Notification notification = new NotificationCompat.Builder(this,"chat")
                .setContentTitle("收到一条聊天消息")
                .setContentText("今天中午吃什么?")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setAutoCancel(true)
                .build();
        manager.notify(1,notification);
    }
    public void sendSubscribeMsg(View view){
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this,"subscribe")
                .setContentTitle("收到一条订阅消息")
                .setContentText("地铁沿线30万商铺抢购中!")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setAutoCancel(true)
                .setNumber(2)
                .build();
        manager.notify(2,notification);
    }

}

8.0以下通知栏的设置:

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(this)
        .setContentText("")
        .setContentTitle("")
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
        .build();
manager.notify(1,notification);

区别:

1、8.0以上需要创建通知渠道

2、8.0以上创建通知时,必须传入渠道id,NotificationCompat.Builder(this)   在8.0及以上版本已经废弃(当然也可以兼容)

补充:

上述为通知栏的基本用法,除此之外,包括:点击内容界面的跳转,设置呼吸灯的闪动频率以及自定义通知栏,

     1.点击内容界面的跳转:

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent intent = new Intent(this, NotificationActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
    Notification notification = new NotificationCompat.Builder(this,"subscribe")
            .setContentTitle("收到一条订阅消息")
            .setContentText("地铁沿线30万商铺抢购中!")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
            .setAutoCancel(true)
            .setNumber(2)
            .setContentIntent(pi)
            .build();
    manager.notify(2,notification);

创建PendingIntent ,在builder中进行设置添加即可。

PendingIntent.getActivity() 获取PendingIntent ,其中需要传的四个参数,第一个参数:Context,第二个参数:自定义唯一的标识符与其他PendingIntent进行区分即可,第三个参数:intent 第四个参数为标识符

2.设置呼吸灯的闪动频率

           .setAutoCancel(true)//设置自动取消,即当点击该通知的时候自动取消
          .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))//设置播放音频
          .setVibrate(new long[] {0,1000,1000,1000})//表示开始首先静止0s,震动1s,然后在静止1s,再震动1s  注意:这个功能需要申请权限
          .setLights(Color.GREEN,1000,1000)//设置手机LED灯,设置成一闪一闪的效果

3.自定义通知栏

            自定义通知栏和使用原生的通知栏区别不大,最主要就是增加了自定义的布局,使用RemoteViews承接,并放入构造器中显示。

           .setContent() 中传入RemoteViews即可

总结:补充里的小知识点既是全部设置builder的各种自定义属性,在此仅仅列出三种,其他如有需要碰到时,再进行补充

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值