Android构建前台服务,以及PendingIntent返回到当前活动的解决办法

来源:互联网 发布:json version 编辑:程序博客网 时间:2024/06/05 20:49

刚开始编写的时候在处理PendingIntent时,就是简单的让所打开的intent回到活动,但是后来发现这样实际上只是新建了一个相同的活动覆盖住了正在进行的活动上,就像写的音乐播放器,在后台的时候若我点击通知栏里的前台服务,会打开了一个新的音乐播放器活动覆盖在正在播放音乐的活动的音乐上面,并不是把后台正在进行的音乐活动调出来。最后解决方法如下:

在AndroidManifest.xml中修改当前活动为singleTask或者singleTop

<activity            android:name=".MusicPlay"            android:launchMode="singleTask"></activity>
这样点击HOME键活动后台运行,点击前台服务不会new出一个新的活动。
前台服务的构建方法:重写Service的onCreate()和onDestroy()方法

@Override    public void onCreate(){        super.onCreate();        Intent nfIntent = new Intent(this, MusicPlay.class);        PendingIntent pi = PendingIntent.getActivity(this,0,nfIntent,0);        Notification notification = new NotificationCompat.Builder(this)                .setContentTitle("Dance团音乐播放")                .setContentText(" 正在播放,点击返回音乐")                .setWhen(System.currentTimeMillis())                .setSmallIcon(R.drawable.music)                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.drawable.dance))                .setContentIntent(pi)                .build();        startForeground(1,notification);    }    @Override    public void onDestroy(){        super.onDestroy();    }
启动服务:

//启动前台服务        Intent ServiceIntent = new Intent(this,MusicService.class);        startService(ServiceIntent);
销毁服务:

//销毁前台服务                Intent intent = new Intent(this,MusicService.class);                stopService(intent);