整体思路:
需求:需要发送一个Notification,点击notification需要跳跃到指定的Activity界面
需要的东东:需要NotificationManager的实例manager、需要Notification的实例notification:notification用new Notification.Builder(Context context).setxxx.build()来得到实例,记得要setContentIntent(PendingIntent pi)来实现点击事件。
最后manager.manage(NOTIFICATION_ID , notification)提交。
在响应启动的Activity的oncreate()方法中新建一个NotificationManager的实例manager,调用manager.cancle(NOTIFICATION_ID),来取消通知栏的notificaton
package com.example.notificationtest;
import android.support.v7.app.ActionBarActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button button;
public static final int NOTIFICATION_ID = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.send_notification);
button.setOnClickListener(this);
//取消通知栏的notifiation
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.send_notification){
Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show();
//建立一个PendingIntent
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//在setContentIntent中用到了前面的PendingIntent
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("this is title")
.setContentInfo("this is info")
.setTicker("i am comming")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pi)
.build();
//别忘了最后的提交
manager.notify(NOTIFICATION_ID, notification);
}
}
}