Android 里的各种通信方式(三)

四:notifation通知

Notifation通知栏会在屏幕上方向用户提示信息 但是不会打断用户正在阅读的内容,除非用户手动将 Notifation通知栏拉下。 Notifation的好处就是在于不会影响用户的操作,比如用户正在阅读非常重要的信息这时候帮他直接打开一个activity会非常不合适 因为直接影响到了他当时的操作行为 所以Notifation就出来了。建议大家在开发中遇到可能打断用户使用的情况下都去使用Notifation通知栏。

public class NotificationActivity extends Activity {

NotificationManager mManager = null;

Notification notification =null;

@Override

protected void onCreate(Bundle savedInstanceState) {

setContentView(R.layout.notification);

// 得到通知消息的管理器对象,负责管理 Notification 的发送与清除消息等

mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

// 创建Notification对象 参数分别代表 通知栏 中显示的图标 显示的标题 显示的时间

notification = new Notification(R.drawable.jay,

"Android专业开发群", System.currentTimeMillis());

// 设置在通知栏中点击后Notification自动消失

notification.flags = Notification.FLAG_AUTO_CANCEL;

//设置点击后转跳的新activity

Intent intent = new Intent(this, MyShowActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);

//通过bundle可以带一些数据过去 这里将字符串传递了过去

Bundle bundle = new Bundle();

bundle.putString("name", "从Notification转跳过来的");

intent.putExtras(bundle);

//设置通知栏中显示的内容

PendingIntent contentIntent = PendingIntent.getActivity(this,

R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);

notification.setLatestEventInfo(this, "Android专业开发群",

"QQ群号 164257885", contentIntent);

Button button0 = (Button)findViewById(R.id.button0);

button0.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

//打开这个Notification通知

mManager.notify(0, notification);

}

});

Button button1 = (Button)findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

//关闭这个Notification通知

mManager.cancelAll();

}

});

super.onCreate(savedInstanceState);

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容