1.简单的一个布局,通过Button来发送通知
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/send_notice"
android:text="Send notice"
android:textAllCaps="false"/>
</LinearLayout>
2.整体的Java代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
//只在Android 8.O之上需要渠道,这里的第一个参数要和下面的channelId一样,8.0以下没有渠道这一说法
NotificationChannel notificationChannel = new NotificationChannel("2","name",NotificationManager.IMPORTANCE_HIGH);//通知重要度,DEFAULT及以上,通知时手机默认会有振动
//如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道,通知才能正常弹出
manager.createNotificationChannel(notificationChannel);
}
Intent intent = new Intent(this,NotificationActivity.class);
//pendingIntent可以理解为延迟执行的intent,四个参数注意第一个是context第三个是上面创建的intent对象就行了,第二个和第四个通常情况下传入0就可以了
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
//注意这里的NotificationCompat.Builder的用法已经变了,它接受两个参数,第一个不用说就是context,第二个是Channel的id,这里的id必须和上面设置的id保持一致
Notification notification = new NotificationCompat.Builder(this,"2")
.setContentTitle("this is content title") //设置通知的标题内容
.setContentText("this is content text") //设置通知的正文内容
.setWhen(System.currentTimeMillis()) //指定通知被创建的时间
.setSmallIcon(R.drawable.notification) //设置通知的小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.notification)) //设置通知的大图标
.setContentIntent(pendingIntent) //接受pendingIntent对象
.setVibrate(new long[] {0,1000,1000,1000}) //设置手机震动
.setLights(Color.GREEN,1000,1000) //设置LED灯
.setAutoCancel(true) //点击通知后,通知会自动取消
.build();
manager.notify(1,notification); //让通知显示出来
break;
default:
break;
}
}
}
注意:因为设置了手机震动,所以需要声明权限
<uses-permission android:name="android.permission.VIBRATE"/>
3.通知的布局
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="24sp"
android:text="this is notification layout"/>
</RelativeLayout>