您的位置:首页 > 其它

StatusBar的使用_例子讲解

2012-04-12 13:00 239 查看
Notification是一般是在Service这种后台服务中发起的,当后台服务要通知用户某一事项时,就发起一个Notification,然后通过这个Notification启动相应的Activity,而Service自己不应该启动Activity.

生成Notification要用到两个类,一个是Notification,两一个是NotificationManager.其实不建议通过Notification的构造函数创建Notification,而是用Notification.Builder来帮助生成。

生成一个Notification的步骤:

1. 得到一个NotificationManger的引用。这个要通过getSystemService(NOTIFICATION_SERVICE)方法来得到.

2. 生成一个Notification对象:

3. 定义Notification的内容和PendingIntent

4. 将Notification传递给NotificationManager

以下为程序例子:在MainActivity中有一个按钮,当点击按钮后会产生一个Notification在status bar中,然后点击打开这个Notification会打开ActionNotification这个Activity.

MainActivity.java:

public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button button = (Button) findViewById(R.id.btn_notice);
button.setOnClickListener(new OnClickListener()
{

public void onClick(View v)
{
setNotification();
}
});
}

private void setNotification()
{
// 首先得到NotificationManager,通过getSystemService()方法得到
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 生成一个Notification,其实不建议直接采用构造方法,而是用Notification.Builder类生成Notification
Notification notice = new Notification(R.drawable.close2, "have downloaded", System.currentTimeMillis());
// 定义Notification的信息和PendingIntent
Intent intent = new Intent(this, ActionNotification.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notice.setLatestEventInfo(this, "下载完成", "请打开查看", contentIntent);
// 将Notification传递给NotificationManager
nm.notify(1, notice);
}
}


ActionNotification.java:

public class ActionNotification extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("歌曲 一千年以后 下载完成");
LinearLayout layout = new LinearLayout(this);
layout.addView(textView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

setContentView(layout);
}
}


程序运行结果:







为Notification增加声音提醒:

增加系统默认声音:

notification.defaults |= Notification.DEFAULT_SOUND;

增加自定义声音:

notification.sound = Uri.parse("file:///sdcard/notification/ring.mp3");

为Notification增加震动提醒:

增加系统默认震动:

notification.defaults |= Notification.DEFAULT_VIBRATE;

增加自定义震动:

long[] vibrate = {0. 100. 200, 300};

notification.vibrate = vibrate;

如果需要使用震动功能,需要加入权限:<uses-permission android:name="android.permission.VIBRATE" />

为Notification加入灯闪提醒:

增加系统默认灯闪:

notification.defaults |= Notification.DEFAULT_LIGTHS;

增加自定义灯闪:

notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: