public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationCompat.Builder builder=new NotificationCompat.Builder(MyService.this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.setTicker("來信息了")
.setContentTitle("這是標題")
.setContentText("這是內容")
.setWhen(System.currentTimeMillis())
.setSubText("這是SubText");
Intent intent1=new Intent(MyService.this,Three.class);
/**
* 首先發(fā)送了一條Notification到通知欄上排作,
* 然后這時僚饭,退出程序,即主頁面已經(jīng)不存在了袍祖,這時我們去點擊Notification,
* 跳轉到指定界面境蔼,然后我們按下Back鍵山涡,發(fā)現(xiàn)直接回到系統(tǒng)界面而不是程序主界面。
* 現(xiàn)在大多數(shù)android應用都是在通知欄中如果有Notification通知的話必怜,點擊它肉拓,
* 然后會直接跳轉到對應的應用程序的某個界面,這時如果回退棚赔,會返回到該應用程序的主界面帝簇,
* 而不是系統(tǒng)的主界面徘郭。所以用上面這種PendingIntent的做法達不到目的靠益。這里我們使用TaskStackBuilder來做。
*/
TaskStackBuilder builder1=TaskStackBuilder.create(MyService.this);
builder1.addParentStack(Three.class);
builder1.addNextIntent(intent1);
PendingIntent pendingIntent=builder1.getPendingIntent(1,PendingIntent.FLAG_UPDATE_CURRENT);
//如果單純的點擊跳轉到某個頁面残揉,用下面這個PendingIntent就可以
//PendingIntent pendingIntent= PendingIntent.getActivity(MyService.this,1,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notification=builder.build();
//啟動前臺Notification
startForeground(100,notification);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
//取消前臺Notification用這個方法
stopForeground(true); }}
例如點擊通知跳轉到Three.class頁面胧后,點擊返回時回退到Second.class,需要添加
<activity
android:name=".Three"
//添加parentActivityName屬性
android:parentActivityName=".Second" />