android平台专门提供饿了NotificationManager来管理状态栏信息,提供Notification来处理这些信息。
首先通过getSystemService方法得到NotificationManager对象;
然后通过notify方法来执行一个Motification快讯。
下面是一个demo:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class NotificationActivity extends Activity {
/** Called when the activity is first created. */
private Button m_Button1;
// 声明通知管理器
private NotificationManager notificationManager = null;
private Intent intent = null;
private PendingIntent pendingIntent = null;
// 声明Notification对象
private Notification notification = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 初始化NotificationManager对象
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 获得Button
m_Button1 = (Button) findViewById(R.id.button1);
// 点击通知时转移内容
intent = new Intent(getApplicationContext(), Activity02.class);
// 主要设置点击通知的时显示内容的类
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
intent, 0);
// 构造Notification对象
notification = new Notification();
m_Button1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// 设置通知在状态栏显示的图标
notification.icon = R.drawable.ic_launcher;
// 当我们点击通知时显示的内容
notification.tickerText = "Button1通知内容。。";
// 通知时发出的声音
notification.defaults = Notification.DEFAULT_SOUND;
// 设置同时显示的参数
notification.setLatestEventInfo(getApplicationContext(),
"Button1", "Button01的通知", pendingIntent);
// 可以理解为执行这个通知
notificationManager.notify(0, notification);
}
});
}
}
main.xml就不用写了!很简单。就是一个button和一个TextView
main2.xml中只有一个TextView用来显示一段string
所以Activity2中只有一个TextView
功能说明:点击NotificationActivity 中的Notification之后跳转到Activity2中,并显示main2中的内容。
不要忘了在AndroidManifest中注册Activity2
来源:http://blog.youkuaiyun.com/crazy1235/article/details/7268840