Notification 小练习

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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;

public class MainActivity extends AppCompatActivity {

final static int NOT_ID = 0x111;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            creatNotify();
        }
    });
    findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(NOT_ID);
        }
    });
}

@RequiresApi(api = Build.VERSION_CODES.O)
void creatNotify() {
    //指定一个ID,这个ID要和后面生成Channel ID一样,意思就是说这个通知放到将来在系统哪个频道发出。
    // 这个ID是channel的ID
    Notification.Builder builder = new Notification.Builder(this, "channel_id");
    builder.setSmallIcon(R.drawable.tools);
    builder.setContentTitle("标题")
            .setTicker("this is ticker")
            .setAutoCancel(true)
            .setContentIntent(PendingIntent.getActivity(MainActivity.this, 1, new Intent(MainActivity.this, otherActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
    Notification notification = builder.build();
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //定义一个频道ID,这个频道用来发送跟这个频道对应ID一样的通知。
    // 这个ID是channel的ID
    NotificationChannel notificationChannel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_HIGH);
    notificationManager.createNotificationChannel(notificationChannel);
    // 这个ID的作用是为notification绑定一个ID,
    // 是notification的在系统中的编号。为了后面删除该通知时调用这个ID
    notificationManager.notify(NOT_ID, notification);
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值