1、设置点击事件发生通知,并且传入字符进去
public class MainActivity extends Activity implements OnClickListener{
private NotificationManager mManager = null;
private Notification notification = null;
private Button button1;
private Button button0;
private final static String LOG_TAG = MainActivity.class.getSimpleName();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initNotitficationManager();
}
public void initNotitficationManager(){
Log.i(LOG_TAG, "initNotitficationManager");
mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
// 设置点击后转跳的新activity
Intent intent = new Intent(this, OtherActivity.class);
// 通过bundle可以带一些数据过去 这里将字符串传递了过去
Bundle bundle = new Bundle();
bundle.putString("name", "从Notification转跳过来的");
intent.putExtras(bundle);
// 设置通知栏中显示的内容
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// builder.setSmallIcon(R.drawable.ic_caoyu);
builder.setTicker("dandan通知");
builder.setContentTitle("this is the title");
builder.setContentText("我有一百种方法让你呆不下去~");
builder.setSubText("——记住eee");
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.drawable.ic_sanwenyu);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
notification = builder.build();
}
public void initView(){
button0 = (Button) findViewById(R.id.btn);
button1 = (Button) findViewById(R.id.btn1);
button0.setOnClickListener(this);
button1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn:
mManager.notify(0, notification);
break;
case R.id.btn1:
mManager.cancelAll();
break;
}
}
}
2、在跳转到的OtherActivity中显示MainActivity传来的数据,并且清空通知栏的通知提示
public class OtherActivity extends Activity {
private TextView tv;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
Log.i("OtherActivity", getIntent().getExtras().getString("name"));
tv = (TextView) findViewById(R.id.tv);
tv.setText(getIntent().getExtras().getString("name"));
NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager.cancel(0);
}
}
PendingIntent主要提供了几个静态的方法获取其实例,可以根据需求来选择是使用getActivity()方法、getBroadcast()方法,还是getService()方法,所接收到的参数是相同的
Notification setAutoCancel(true) 不工作时,
builder..setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0) 可以取消通知栏的消息