感觉通知这个功能每个版本都会改变,
通知的作用呢,
- 接送各种通知消息吧,比如说极光推送,小米推送
- 音乐播放器app都会用Notification来控制app,打到操作简单的目的
setSmallIcon是必要参数,不填写会报错
创建Notification
- 创建NotificationCompat.Builder 对象
- 通过builder创造notification对象
- 获得notificationManager对象
- 发送notification
public class MainActivity extends AppCompatActivity {
int num=1;
private Button button,button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,NewActivity.class);
PendingIntent pIntent=PendingIntent.getActivity(MainActivity.this,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
//创建NotificationCompat.Builder 对象
NotificationCompat.Builder builder=new NotificationCompat.Builder(MainActivity.this);
//设置通知图标
builder.setSmallIcon(R.mipmap.ic_launcher_round);
builder.setContentTitle("标题"+num++);
builder.setContentText("内容");
//设置Ticker不一定会显示
builder.setTicker("会显示吗");
//设置PendingIntent
builder.setContentIntent(pIntent);
//设置点击后自动取消
// builder.setAutoCancel(true);
//设置点击后不取消
builder.setOngoing(true);
//设置震动
//builder.setVibrate();
//设置声音
//builder.setSound();
//通过builder创造notification对象
Notification notification=builder.build();
//获得notificationManager对象
NotificationManager notificationManager=(NotificationManager)MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
//1表示这个notification的id唯一标识符
notificationManager.notify(num,notification);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationManager notificationManager=(NotificationManager)MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
//notificationManager.cancel(num--);
notificationManager.cancelAll();
}
});
}
private void init() {
button=(Button) findViewById(R.id.button);
button2=(Button) findViewById(R.id.button2);
}
}
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.feng.temp0723.MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="212dp"
android:text="显示notification"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="212dp"
android:text="关闭notification"/>
</LinearLayout>
记住notification的创建流程就好,个人觉得创建起来比较麻烦
先创建builder。然后创建notification的对象,最后创建NotificationManager发生通知消息
一般通知消息的话,第三方推送,推荐小米推送和华为推送吧,感觉现在用激光推送的比较少了,毕竟,华为和小米是系统级别的推送,性能更好点,
ps:听说工信部要统一国内android推送,也不知道落实要多久
有时间做一个模仿音乐播放器的自定义notification