zoukankan      html  css  js  c++  java
  • Android组件通讯之Pending Intent与Notification

    使用系统的通知服务可以可视化本来无法显示的广播信息

    以下为实现方法,涉及了3个类:NotificationManager,Notification,PendingIntent

     1 public class MainActivity extends Activity {
     2 
     3     private Button notifyBtn = null;
     4     private NotificationManager manager = null;
     5     private Notification notification = null;
     6     
     7     @Override
     8     protected void onCreate(Bundle savedInstanceState) {
     9         super.onCreate(savedInstanceState);
    10         setContentView(R.layout.activity_main);
    11         
    12         notifyBtn = (Button) findViewById(R.id.NotifyBtn);
    13         notifyBtn.setOnClickListener(new NotifyBtnListener());
    14         
    15     }
    16     
    17     private class NotifyBtnListener implements OnClickListener {
    18 
    19         @Override
    20         public void onClick(View v) {
    21             // 获取系统通知服务,转型为通知管理器
    22             MainActivity.this.manager = (NotificationManager) MainActivity.this.getSystemService(NOTIFICATION_SERVICE);
    23             
    24             // 设置通知出现时在屏幕上方滚动的小图标和提醒的文字内容
    25             MainActivity.this.notification = new Notification(R.drawable.ic_launcher, "有通知", System.currentTimeMillis());
    26             
    27             // 包装intent为PendingIntent在特定时间触发,此例为点击notification后跳转到目的页,就是自己
    28             Intent intent = new Intent(MainActivity.this, MainActivity.class);
    29             PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    30             
    31             // 设置下拉通知栏之后notification显示的标题和内容,还有所需的PendingIntent
    32             MainActivity.this.notification.setLatestEventInfo(MainActivity.this, "通知标题", "通知内容", contentIntent);
    33             
    34             // 通知管理器发出通知,第一个参数是个字符串标识,一般为空; 第二个参数是此notify的一个唯一整型标识,最后则为notification对象
    35             manager.notify("Notify_A", 0, notification);
    36         }
    37         
    38     }
    39     
    40 }

    效果如下图:

    上方滚动条:

    下拉通知中心:

    点击它就会跳转到目的Activity或其他组件

  • 相关阅读:
    Android Fragment(一)
    Android github上的好的开源项目汇总
    Android ScrollView 嵌套ListView的替代方案
    Android cannot be cast to android.app.Fragment
    js css加时间戳
    WPF无边框实现拖动效果
    分析器错误消息: 未能加载类型
    微信红包功能(含示例demo)
    ABP缓存示例
    微信白名单配置与检验
  • 原文地址:https://www.cnblogs.com/moka/p/3065257.html
Copyright © 2011-2022 走看看