一、通知的用法
当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。相比于广播接收器和服务,在活动里创建通知的场景还是比较少的,因为一般只有当程序进入到后台的时候我们才需要使用通知。
- 获得NotificationManager 的实例
- 创建一个 Notification 对象
- 设定通知的布局
- 调用 NotificationManager 的 notify()方法
二、具体实例——通过点击按钮来发出一条通知
- 建立布局
<LinearLayout 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:orientation="vertical" >
<Button
android:id="@+id/send_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send notice" />
</LinearLayout>
- MainActivity
public class MainActivity extends ActionBarActivity {
private Button button;
private NotificationManager manager;
private Notification.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.send_notice);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder = new Notification.Builder(MainActivity.this);
Intent intent = new Intent(MainActivity.this,
MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
MainActivity.this, 0, intent, 0);
builder.setContentIntent(contentIntent);
builder.setTicker("这是一个通知");
builder.setContentTitle("通知");
builder.setContentText("hello");
builder.setDefaults(Notification.DEFAULT_ALL);
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
manager.notify(1, notification);
}
});
}
}
本文将介绍如何在Android应用中通过点击按钮发送通知,包括创建布局、设置NotificationManager实例、创建Notification对象并调用notify()方法的完整过程。
2399

被折叠的 条评论
为什么被折叠?



