新建一个 NotificationTest项目,并修改 activity_main.xml 中的代码,如下所示:
<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>
布局文件非常简单,里面只有一个 Send notice 按钮,用于发出一条通知。接下来修改
MainActivity中的代码,如下所示:
public class MainActivity extends Activity implements OnClickListener {
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.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());
notification.setLatestEventInfo(this, "This is content title","This is content text", null);
manager.notify(1, notification);
break;
default:
break;
}
}
}