易采站长站为您分析Android中通知Notification使用实例,实现振动,灯光,声音等效果,感兴趣的小伙伴们可以参考一下
本文实例讲解了通知Notification使用方法,此知识点就是用作通知的显示,包括振动、灯光、声音等效果,,具体内容如下
效果图:
MainActivity:
import java.io.File;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
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对象来存储通知所需的各种信息
//第一个参数为图标
//第二个参数用于指定通知的ticker内容
//第三个参数用于指定通知被创建的时间,以毫秒为单位
Notification notification = new Notification(
R.drawable.ic_launcher, "This is ticker text",
System.currentTimeMillis());
//此处设置点击的activity的跳转
//第一个参数依旧是Context
//第二个参数一般用不到,所以用0表示取默认值
//第三个参数就是一个Intent对象
//FLAG_CANCEL_CURRENT:如果当前系统中已经存在一个相同的PendingIntent对象,
// 那么就将先将已有的PendingIntent取消,然后重新生成一个PendingIntent对象。
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
//设置通知的布局
//第一个参数为Context
//第二个参数用于指定通知的标题
//第三个参数用于指定通知的征文内容
//第四个参数用于传入PendingIntent对象,用于设置点击效果
notification.setLatestEventInfo(this, "This is content title",
"This is content text", pi);
// //设置在通知发出的时候的音频
// Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));
// notification.sound = soundUri;
//
// //设置手机震动
// //第一个,0表示手机静止的时长,第二个,1000表示手机震动的时长
// //第三个,1000表示手机震动的时长,第四个,1000表示手机震动的时长
// //此处表示手机先震动1秒,然后静止1秒,然后再震动1秒
// long[] vibrates = {0, 1000, 1000, 1000};
// notification.vibrate = vibrates;
//
// //设置LED指示灯的闪烁
// //ledARGB设置颜色
// //ledOnMS指定LED灯亮起的时间
// //ledOffMS指定LED灯暗去的时间
// //flags用于指定通知的行为
// notification.ledARGB = Color.GREEN;
// notification.ledOnMS = 1000;
// notification.ledOffMS = 1000;
// notification.flags = Notification.FLAG_SHOW_LIGHTS;
//如果不想进行那么多繁杂的这只,可以直接使用通知的默认效果
//默认设置了声音,震动和灯光
notification.defaults = Notification.DEFAULT_ALL;
//使用notify将通知显示出来
//第一个参数是id,要爆炸为每个通知所指定的id是不同的
//第二个参数就是Notification对象
manager.notify(1, notification);
break;
default:
break;
}
}
}













