前臺服務(wù)

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("這是內(nèi)容")                
.setWhen(System.currentTimeMillis())                
.setSubText("這是SubText");        
Intent intent1=new Intent(MyService.this,Three.class);        
/**        
 * 首先發(fā)送了一條Notification到通知欄上,         
* 然后這時,退出程序,即主頁面已經(jīng)不存在了,這時我們?nèi)c擊Notification,         
* 跳轉(zhuǎn)到指定界面,然后我們按下Back鍵,發(fā)現(xiàn)直接回到系統(tǒng)界面而不是程序主界面。        
 * 現(xiàn)在大多數(shù)android應(yīng)用都是在通知欄中如果有Notification通知的話,點擊它,         
* 然后會直接跳轉(zhuǎn)到對應(yīng)的應(yīng)用程序的某個界面,這時如果回退,會返回到該應(yīng)用程序的主界面,         
* 而不是系統(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);        
//如果單純的點擊跳轉(zhuǎn)到某個頁面,用下面這個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);    }}

例如點擊通知跳轉(zhuǎn)到Three.class頁面,點擊返回時回退到Second.class,需要添加

<activity    
android:name=".Three"   
//添加parentActivityName屬性
 android:parentActivityName=".Second" />
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容