安卓开发 手机通知栏发送提醒

activity_main.xml文件按钮代码:

<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="26dp"
android:layout_marginTop="14dp"
android:text="点击发送" />
<Button
android:id="@+id/button2"
android:layout_below="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_marginLeft="26dp"
android:layout_marginTop="14dp"
android:text="点击取消" />

 

MainActivity.java文件代码:  

public class MainActivity extends Activity implements OnClickListener{
Button button1;
Button button2;
NotificationManager manager;
int nid;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
Toast.makeText(this, "发送通知", Toast.LENGTH_SHORT).show();
sendNotification();
break;
case R.id.button2:
Toast.makeText(this, "取消通知", Toast.LENGTH_SHORT).show();
manager.cancel(nid);
break;
}
}

private void sendNotification(){
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pindtent = PendingIntent.getActivity(this, 0, intent, 0);
Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.img1);//图标
builder.setTicker("hello");//手机状态栏的提示;
builder.setWhen(System.currentTimeMillis());//设置时间
builder.setContentTitle("通知的通知标题");
builder.setContentText("sendnotification 发送的通知");//通知内容
builder.setContentIntent(pindtent);//点击后意图
//builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音
//builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯
//builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
builder.setDefaults(Notification.DEFAULT_ALL);//设置提示声音,震动,指示灯
Notification not = builder.build();
manager.notify(nid,not);
}

}

posted @ 2017-04-05 09:18  攻城西施  阅读(1394)  评论(0编辑  收藏  举报