美文网首页
前台服务

前台服务

作者: 山岭巨人郭敬明 | 来源:发表于2016-12-08 22:02 被阅读0次
    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);        
    /**        
     * 首先发送了一条Notification到通知栏上,         
    * 然后这时,退出程序,即主页面已经不存在了,这时我们去点击Notification,         
    * 跳转到指定界面,然后我们按下Back键,发现直接回到系统界面而不是程序主界面。        
     * 现在大多数android应用都是在通知栏中如果有Notification通知的话,点击它,         
    * 然后会直接跳转到对应的应用程序的某个界面,这时如果回退,会返回到该应用程序的主界面,         
    * 而不是系统的主界面。所以用上面这种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" />
    

    相关文章

      网友评论

          本文标题:前台服务

          本文链接:https://www.haomeiwen.com/subject/pnosmttx.html