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);


}
});


}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM