新建一个Android的项目 通知栏的基本用法
修改activity_main.xml的代码,如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/send_notice" android:onClick="click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send notice" /> </RelativeLayout>
布局文件非常简单,里面只有一个Send Notice 按钮,用于发送一条通知。
新建一个Activity界面,并需要准备一个新的布局文件,notification_layout.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="This is notification layout " android:textSize="24sp" /> </RelativeLayout>
新建NotificationActivity继承Activity,在这里加载刚才定义的布局文件。
package com.example.tongzhi; import android.app.Activity; import android.app.NotificationManager; import android.os.Bundle; public class NotificationActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置点击通知栏信息得到的界面 setContentView(R.layout.notification_layout); // 将通知栏的信息消失 NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.cancel(1); } }
接下来修改,MainActivity中的代码
package com.example.tongzhi; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view) { switch (view.getId()) { case R.id.send_notice: NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // 第三个参数指定通知信息被创建的具体时间 Notification notification = new Notification( R.drawable.ic_launcher, "This is ticker text", System.currentTimeMillis()); // 响应点击通知信息,PendingIntent Intent intent = new Intent(this, NotificationActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); // 对通知的布局进行设定,下面的方法就可以给通知设置一个标准的布局 notification.setLatestEventInfo(this, "This is content title", "This is content text", pi); // 调用NotificationManager的notify()方法让通知显示出来 manager.notify(1, notification); break; default: break; } } }
时间: 2024-10-21 19:45:17