消息通知 Notification 点击切换回原Activity


一个简单的应用场景:假如用户打开Activity以后,按Home键,此时Activity 进入-> onPause() -> onStop() 不可见。代码在此时机发送一个Notification到通知栏。当用户点击通知栏的Notification后,又重新onRestart() -> onStart() -> onResume() 切换回原Activity。

效果图:



package com.example.notification;

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.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

	private final int NOTIFICATION_ID = 0xa01;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(this.getClass().getName(), "onCreate()");
		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();

		// 当用户下来通知栏时候看到的就是RemoteViews中自定义的Notification布局
		RemoteViews rv = new RemoteViews(getPackageName(),
				R.layout.notification);
		rv.setImageViewResource(R.id.image, R.drawable.qq);
		rv.setTextViewText(R.id.title, "清清");
		rv.setTextViewText(R.id.text, "烟花易冷,很好听!");
		notification.contentView = rv;

		// 需要注意的是,作为选项,此处可以设置MainActivity的启动模式为singleTop,避免重复新建onCreate()。
		Intent intent = new Intent(this, MainActivity.class);

		// 当用户点击通知栏的Notification时候,切换回MainActivity。
		PendingIntent pi = PendingIntent.getActivity(this, 0x05, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		notification.contentIntent = pi;

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

		// 通知的时间
		notification.when = System.currentTimeMillis()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值