学习Notification中,创建Notification实例的时候发现,使用构造函数传入参数的方法已经被弃用了;
而且,使用notification对象也调用不了setLatestEventInfo()方法;API建议用Notificaion.Builder,那就用这个吧~
简单的实现一个通知跳转功能:
主类创建通知:
public class MainActivity extends AppCompatActivity {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)//最小编译版本问题,加个声明就好
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Notification notification =new Notification
// (R.mipmap.ic_launcher,"我是ticker",System.currentTimeMillis());
//实例化通知管理
final NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//跳转到Main2Activity
Intent intent = new Intent(this, Main2Activity.class);
//实例化一个延迟意图,
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{intent}
, PendingIntent.FLAG_CANCEL_CURRENT);
//给通知添加标题,内容,图标,设置动作
final Notification notification = new Notification.Builder(this)
.setContentTitle("我是内容标题")
.setContentText("我是内容")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build();
findViewById(R.id.am_btnNotif).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击启动通知
notificationManager.notify(1, notification);
}
});
}
}
通知类就一个TextView显示信息:这是Main2Activity的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/am2_tvMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/am2_tvMsg"
android:textSize="24sp" />
</RelativeLayout>
通知类:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
//完成跳转后,取消通知
notificationManager.cancel(1);
}
}
点击后完成跳转,并且通知图标也没了~