Android 普通通知栏新方法,现在需要创建通知渠道才可以
先看看效果看看是不是你想要的
点击后
话不多所,贴代码
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainSendMessage">
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送通知"
/>
</LinearLayout>
activity代码:
package com.example.love5;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
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 MainSendMessage extends AppCompatActivity {
private Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_send_message);
b1 = findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//创建通知渠道实例
//并为它设置属性
//通知渠道的ID,随便写
String id = "channel_01";
//用户可以看到的通知渠道的名字,R.string.app_name就是strings.xml文件的参数,自定义一个就好了
CharSequence name = getString(R.string.app_name);
//用户可看到的通知描述
String description = getString(R.string.app_name);
//构建NotificationChannel实例
NotificationChannel notificationChannel =
new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
//配置通知渠道的属性
notificationChannel.setDescription(description);
//设置通知出现时的闪光灯
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
//设置通知出现时的震动
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 100});
//在notificationManager中创建通知渠道
manager.createNotificationChannel(notificationChannel);
//蓝色字是个新方法,旧的被api放弃了
Notification notification = new NotificationCompat.Builder(MainSendMessage.this, id)
.setContentTitle("标题")
.setContentText("内容666666666666666666666666666")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.tubiao)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.coffee))
.build();
manager.notify(1, notification);
}
});
}
}
本文来自博客园,作者:岑惜,转载请注明原文链接:https://www.cnblogs.com/c2g5201314/p/10556282.html
响应开源精神相互学习,内容良币驱除劣币