问题描述:在布局main.xml中点击按钮后,系统接收到一个通知显示在后台(类似短信微信),下拉手机点击通知,跳转到相应的界面。
main.xml中的按钮
如下:
android:id="@+id/send_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="send notice"
/>
创建一个NotificationTest 的活动加载main.xml这个布局:
public class NotificationTest extends Activity implements OnClickListener{
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.send_notice:
//定义一个通知管理器,从系统服务中得到NOTIFICATION_SERVICE,从而管理这个服务。
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//创建Notification对象,参数为通知图标,标题,通知创建的时间
Notification notication = new Notification(R.drawable.ic_launcher,"this is ticker text",System.currentTimeMillis());
//创建活动意图,即链接到另外的一个活动
Intent intent = new Intent(this,NotificationActivity.class);
//不立即启动intent,PendingIntent 倾向于在合适的时机去执行某个动作,延迟意图。
//PendingIntent对象的参数,上下文,0,Intent对象,PendingIntent的行为。
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//调用Notification对象 的 setLatestEventInfo()方法给通知设置一个标准的布局
//参数为上下文,通知标题,内容,PendingIntent对象。
notication.setLatestEventInfo(this, "this is content title", "this is content text", pi);
//通知管理器的notify()方法显示通知,参数为通知设定的id,通知对象。
manager.notify(1,notication);
break;
default:
break;
}
}
}
好了,写完这个活动以后要接着在跳转的NotificationActivity活动中打开通知,加载新界面布局
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
//建一个通知管理器对象目的是打开新界面以后要关闭通知,那个“1”就是要关闭通知的id。
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);
}
ok,到此处一个简单的通知就搞定了。
共同进步。