Android Notification入门

本文通过一个简单示例展示了如何在Android应用中实现消息推送功能。包括创建通知、设置通知内容及图标、发送和取消通知等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android Notification为消息推送。具体使用方法将通过一个Demo演示。

public class MyNotification extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        //以下为界面布局代码。
        LinearLayout linearLayout = new LinearLayout(this);
        TextView textView = new TextView(this);
        Button btShow = new Button(this);
        btShow.setText("send message");
        Button btHide = new Button(this);
        btHide.setText("cancel message");
        linearLayout.addView(textView);
        linearLayout.addView(btShow);
        linearLayout.addView(btHide);
        setContentView(linearLayout);
        btShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });
        btHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancle();
            }
        });
    }

    void sendMessage() {
        //发送推送消息
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher, "hello world", System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults = notification.DEFAULT_SOUND | notification.DEFAULT_VIBRATE;

        Intent intent = new Intent(getBaseContext(), MyTextView.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        notification.setLatestEventInfo(this, "title", "content", pendingIntent);

        manager.notify(notificationId, notification);
    }

    void cancle() {
        //清空推送消息
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(notificationId);
    }

    //标识消息的Id
    private static final int notificationId = 1;
}

通过这个简单的Demo就可以初步使用Notification了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值