您的位置:首页 > 其它

通知 notification

2015-11-27 10:13 471 查看
package com.example.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

private final int NOTIFICATION_ID = 105;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
sendNotification();

}
});

Button clear = (Button) findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
clearNotification();
}
});
}

private void sendNotification(){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("来自徐华清");
mBuilder.setContentText("烟花易冷,很好听!");

Notification notification = mBuilder.build();

//缺省设置为当发送通知到通知栏的时候:提示声音+震动
notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;

//通知的时间
notification.when = System.currentTimeMillis();

//发送到手机的通知栏
notificationManager.notify(NOTIFICATION_ID, notification);

}

private void clearNotification(){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
}


<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.notification.MainActivity" >

<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送通知" />

<Button
android:id="@+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="清除通知" />

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: