<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/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="94dp"
android:layout_marginTop="176dp"
android:text="取消消息"" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnCancel"
android:layout_alignLeft="@+id/btnCancel"
android:layout_marginBottom="91dp"
android:text="发送消息" />
</RelativeLayout>
package com.example.notificationdemo;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button btnSend,btnCancel;
NotificationManager manager;
int Notification_ID=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
btnSend = (Button) findViewById(R.id.btnSend);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnSend.setOnClickListener(this);
btnCancel.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSend:
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("开会");
builder.setContentTitle("下午开会");
builder.setContentText("去人民大会堂开会");
builder.setDefaults(Notification.DEFAULT_ALL);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,1, intent, 0);
builder.setContentIntent(pendingIntent);
Notification notification = builder.build();//4.1版本之后
manager.notify(Notification_ID,notification);
break;
case R.id.btnCancel:
manager.cancel(Notification_ID);
break;
}
}
}
将Androidmanifest最低版本改为16