Android开发--Notification和PendingIntent

来源:互联网 发布:以色列旅游 知乎 编辑:程序博客网 时间:2024/05/04 13:38

    手机上方的状态栏用于显示通知消息,实现的方法很简单,只需要记住五个步骤即可(步骤写在源代码中的注释中)。pendingIntent意思是延期执行的Intent,一般用于Notification中,下面这个例子即实现这两个功能:

public class Notification_Activity extends Activity {private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_notification_);button=(Button)findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@SuppressWarnings("deprecation")@Overridepublic void onClick(View v) {// TODO Auto-generated method stub/* * 创建和显示一个Notification需要以下5个步骤 * 1.通过getSystemService方法获得一个NotificationManager对象 * 2.创建一个Notification对象,每一个Notification对应一个Notification对象,在这一步需要 * 设置显示在屏幕上方状态栏的通知消息,通知消息前方的图像资源ID和发出的通知的时间 * 3.由于Notification可以与应用程序脱离,所以需要创建一个PendingIntent对象 * 4.使用Notification的setLatestEventInfo方法设置Notification的详细信息 * 5.使用NotificationManager类的notify方法显示Notification消息,这一步需要指定Notification唯一的ID */NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);Notification notification=new Notification(R.drawable.ic_launcher, "您有新的消息了!", System.currentTimeMillis());PendingIntent pendingIntent=PendingIntent.getActivity(Notification_Activity.this, 0, new Intent(Notification_Activity.this, otherActivity.class), 0);//这行代码的作用是使得这个通知不能被清除//notification.flags=Notification.FLAG_NO_CLEAR;notification.setLatestEventInfo(Notification_Activity.this, "周末时间到", "出去玩吧", pendingIntent);notificationManager.notify(0,notification);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.activity_notification_, menu);return true;}}


原创粉丝点击