android菜鸟进阶之路——使用通知(通知的基本运用)

问题描述:在布局main.xml中点击按钮后,系统接收到一个通知显示在后台(类似短信微信),下拉手机点击通知,跳转到相应的界面。
main.xml中的按钮
如下:
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send notice"
           />


创建一个NotificationTest 的活动加载main.xml这个布局:
public class NotificationTest extends Activity implements OnClickListener{
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    sendNotice = (Button) findViewById(R.id.send_notice);
    sendNotice.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId()){
        case R.id.send_notice:
        //定义一个通知管理器,从系统服务中得到NOTIFICATION_SERVICE,从而管理这个服务。
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);                 
        //创建Notification对象,参数为通知图标,标题,通知创建的时间
        Notification notication = new Notification(R.drawable.ic_launcher,"this is ticker text",System.currentTimeMillis());

        //创建活动意图,即链接到另外的一个活动
        Intent intent = new Intent(this,NotificationActivity.class);

        //不立即启动intent,PendingIntent 倾向于在合适的时机去执行某个动作,延迟意图。
        //PendingIntent对象的参数,上下文,0,Intent对象,PendingIntent的行为。
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        //调用Notification对象 的 setLatestEventInfo()方法给通知设置一个标准的布局
        //参数为上下文,通知标题,内容,PendingIntent对象。
        notication.setLatestEventInfo(this, "this is content title", "this is content text", pi);
        //通知管理器的notify()方法显示通知,参数为通知设定的id,通知对象。
        manager.notify(1,notication);
        break;

        default:
        break;
        }
    }
}

好了,写完这个活动以后要接着在跳转的NotificationActivity活动中打开通知,加载新界面布局
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.notification_layout);
    //建一个通知管理器对象目的是打开新界面以后要关闭通知,那个“1”就是要关闭通知的id。
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.cancel(1);
}

ok,到此处一个简单的通知就搞定了。
共同进步。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值