Android-恢复服务的活动,并摧毁他们的毁灭 [英] Android- Resuming Service in Activity and destroying them on destroy

查看:152
本文介绍了Android-恢复服务的活动,并摧毁他们的毁灭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个 Activty ,当创建启动并绑定与服务。这服务有一个媒体播放器。我想要做的是,如果该活动是恢复服务继续播放等。当活动被破坏,就应该停止服务。到目前为止,我能得到这两个服务继续玩时,活动被重新激活,并创建一个新的活动时,停止该服务,但不能两者都在一起。任何建议或想法?谢谢。低于code:

活动类:

 公共类DUBAudioActivity延伸活动{

    私有静态最后字符串变量= DUBAudioActivity.class.getSimpleName();

    按钮playPauseButtonDUB;
    意图playbackServiceIntentDUB;


    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.sdrplaylist_dubstep);

        playPauseButtonDUB =(按钮)findViewById(R.id.playpausebuttonDUB);

        playbackServiceIntentDUB =新的意图(这一点,DUBAudioService.class);
        Log.d(TAG,创造意图);

        startService(playbackServiceIntentDUB);

        Log.d(TAG,势必服务);
        //
        //设置按钮文本
         playPauseButtonDUB.setText(暂停);
         //设置按钮标签
        playPauseButtonDUB.setTag(1);



        playPauseButtonDUB.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                //设置标签的东西
                最终诠释状态=(整数)v.getTag();
                //创建if语句的按钮进行播放和暂停
                如果(状态== 1){
                    playPauseButtonDUB.setText(播放);
                    v.setTag(0);
                    Log.d(TAG,集标记为0);
                    baServiceDUB.pauseSong();
                    Log.d(TAG,暂停歌);
                }其他{
                    playPauseButtonDUB.setText(暂停);
                    v.setTag(1);
                    Log.d(TAG,集标签1);
                    baServiceDUB.playSong();
                    Log.d(TAG,曲奏响最合时宜);
                }

            }

        });
    //
    }
    私人DUBAudioService baServiceDUB;

    私人ServiceConnection serviceConnectionDUB =新ServiceConnection(){
        公共无效onServiceConnected(组件名的className,的IBinder baBinder){
            baServiceDUB =
            ((DUB​​AudioService.DUBBackgroundAudioServiceBinder)baBinder).getService();
        }

        公共无效onServiceDisconnected(组件名的className){
            baServiceDUB = NULL;
        }
//
    };

    无效doBindService(){
        getApplicationContext()。bindService(playbackServiceIntentDUB,serviceConnectionDUB,
                Context.BIND_AUTO_CREATE);
        Log.d(TAG,做绑定服务);

    }

    @覆盖
    公共无效onResume(){
        getApplicationContext()。bindService(playbackServiceIntentDUB,serviceConnectionDUB,
                Context.BIND_AUTO_CREATE);
            Log.d(TAG,关于恢复+重新绑定服务);
        super.onResume();
    }

    @覆盖
    公共无效的onDestroy(){
        stopService(playbackServiceIntentDUB);
        。getApplicationContext()unbindService(serviceConnectionDUB);

        Log.d(TAG,destroy'd +解除绑定服务);
        //完();
        super.onDestroy();
    }

}
 

服务类:

 公共类DUBAudioService扩展服务实现在preparedListener,OnCompletionListener {

吐司loadingMessage;

私有静态最后字符串变量= DUBAudioService.class.getSimpleName();

    公共布尔isRunning;

    //跟踪播放列表项的
    矢量< PlaylistFile> playlistItems;

    MediaPlayer的媒体播放器;

    字符串的baseUrl =;

    //跟踪哪些项目,从我们的矢量
    INT currentPlaylistltemNumber = 0;

    公共类DUBBackgroundAudioServiceBinder扩展粘合剂{
        DUBAudioService的getService(){
        返回DUBAudioService.this;
        }
    }

    私人最终的IBinder basBinderDUB =新DUBBackgroundAudioServiceBinder();



    @覆盖
    公众的IBinder onBind(意向意图){
        返回basBinderDUB;
    }

    @覆盖
    公共无效的onCreate(){
        Log.v(PLAYERSERVICE,的onCreate);
        媒体播放器=新的MediaPlayer();
        新MusicAsync()执行()。
            Log.d(TAG,execute'd异步);
        mediaPlayer.setOn preparedListener(本);
            Log.d(TAG,在prepared监听器设置);
        mediaPlayer.setOnCompletionListener(本);
            Log.d(TAG,在完成监听器设置);
    }

    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        //如果(!mediaPlayer.isPlaying()){
        // mediaPlayer.start();
        //}
        返回START_STICKY;
    }

    类MusicAsync扩展的AsyncTask<虚空,虚空,虚空> {
        @覆盖
        在preExecute保护无效(){
        }
        @覆盖
        保护无效doInBackground(虚空......为arg0){
            // TODO自动生成方法存根

            //创建空载体
            playlistItems =新矢量< PlaylistFile>();

            // HTTP客户端库
            HttpClient的HttpClient的=新DefaultHttpClient();
            HTTPGET调用getRequest =新HTTPGET(http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u); //我想你可以添加M3U东西在这里

            Log.v(URI,getRequest.getURI()的toString());

            尝试 {
            HTT presponse HTT presponse = httpClient.execute(调用getRequest);
            如果(HTT presponse.getStatusLine()的getStatus code()!= HttpStatus.SC_OK){
            // 错误信息
            Log.v(HTTP错误,HTT presponse.getStatusLine()getReasonPhrase());
            }
            其他 {
                InputStream中的InputStream = HTT presponse.getEntity()的getContent()。
                BufferedReader中的BufferedReader =新的BufferedReader(新的InputStreamReader(InputStream中));

                串线;
                而((行= bufferedReader.readLine())!= NULL){
                    Log.v(PLAYLISTLINE,弊+线);

                    如果(line.startsWith(#)){
                        //元数据
                        //可以做更多与此,但现在不是FO
                    }否则如果(line.length()大于0){
                        字符串文件路径=;
                            如果(line.startsWith(HTTP://)){
                            //假定它是一个完整的URL
                                文件路径=行;
                            } 其他 {
                            //假定它是相对的
                            文件路径= getRequest.getURI()解析(线)的ToString()。
                            }

                            PlaylistFile playlistFile =新PlaylistFile(文件路径);
                            playlistItems.add(playlistFile);
                            }
                            }
                            inputStream.close();
                            }
                            }赶上(ClientProtocolException E){
                                e.printStackTrace();
                            }赶上(IOException异常E){
                            即的printStackTrace();
                            }


                            currentPlaylistltemNumber = 0;
                            如果(playlistItems.size()大于0)
                            {
                            字符串路径=((PlaylistFile)playlistItems.get(currentPlaylistltemNumber))getFilePath()。
                            尝试 {
                                mediaPlayer.setDataSource(路径);

                            。媒体播放器prepareAsync();}
                            赶上(抛出:IllegalArgumentException E)
                            {e.printStackTrace();
                            }赶上(IllegalStateException异常E){
                                e.printStackTrace();
                            }赶上(IOException异常E){
                            e.printStackTrace();}
                            }



            返回null;
        }
        //
        保护无效onPostExecute(无效的结果){
            //为playButton。的setEnabled(假);
        }
    }



    @覆盖
    公共无效ONSTART(意向意图,诠释startId){
        // TODO自动生成方法存根

        super.onStart(意向,startId);
    }

    公共无效的onDestroy(){
        如果(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            Log.d(TAG,乐stopp'd);
        }
        //mediaPlayer.release();
        Log.d(TAG的onDestroy);
    }

    @覆盖
    在prepared公共无效(MediaPlayer的媒体播放器){
        // TODO自动生成方法存根\
        Log.d(TAG,音乐是prepared,将启动);
        mediaPlayer.start();
    }

    公共无效onCompletion(MediaPlayer的_mediaPlayer){
        Log.d(TAG,宋完成,下一首歌);
        mediaPlayer.stop();
        mediaPlayer.reset();
            如果(playlistItems.size()> currentPlaylistltemNumber + 1){
                currentPlaylistltemNumber ++;
            字符串路径=
                ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber))getFilePath();
                尝试 {
                    mediaPlayer.setDataSource(路径);
                    。媒体播放器prepareAsync();
                }赶上(抛出:IllegalArgumentException E){
                    即的printStackTrace();
                }赶上(IllegalStateException异常E){
                    e.printStackTrace();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
    }

    类PlaylistFile {
        字符串文件路径;
            公共PlaylistFile(字符串_filePath){
                文件路径= _filePath;
            }
            公共无效setFilePath(字符串_filePath){
                文件路径= _filePath;
            }
            公共字符串getFilePath(){
                返回文件路径;
            }
        }


    公共无效playSong(){
        Log.d(TAG,start'd);
        mediaPlayer.start();
    }

    公共无效pauseSong(){
        Log.d(TAG,pause'd);
        mediaPlayer.pause();
    }



}
 

解决方案

我说你很幸运,它停止了 - 只有的onPause()是保证所谓当你的活动是中背景。唯一的一次的onDestroy()被称为是当系统决定收回你的应用程序正在使用的内存

唯一可以保证的生命周期电话是:

  • 的onCreate()只有当应用程序是白手起家;
  • onResume()每次运行时,无论是暂停还是第一次创建;
  • 的onPause()每次系统正在您的应用程序在后台时,期。

I currently have an Activty that when created starts and binds with a service. This service has a mediaplayer. What I would like to do is if the activity is resumed then the service keeps playing, etc. When the activity is destroyed, it should stop the service. So far I can get both the service to keep playing when activity is re-activated and the service to stop when a new activity is created but not both together. Any suggestions or ideas? Thanks. Code below:

Activity class:

public class DUBAudioActivity extends Activity{

    private static final String TAG = DUBAudioActivity.class.getSimpleName();

    Button playPauseButtonDUB;
    Intent playbackServiceIntentDUB;


    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdrplaylist_dubstep);

        playPauseButtonDUB = (Button)findViewById(R.id.playpausebuttonDUB);

        playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
        Log.d(TAG, "created intent");

        startService(playbackServiceIntentDUB);

        Log.d(TAG, "bound service");
        //
        //set button text
         playPauseButtonDUB.setText("Pause");
         //set button tag
        playPauseButtonDUB.setTag(1);



        playPauseButtonDUB.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                //set the tag stuff
                final int status = (Integer) v.getTag();
                //create if statement for the button to do play and pause
                if(status==1){
                    playPauseButtonDUB.setText("Play");
                    v.setTag(0);
                    Log.d(TAG, "set tag to 0");
                    baServiceDUB.pauseSong();
                    Log.d(TAG, "pause song");   
                }else{
                    playPauseButtonDUB.setText("Pause");
                    v.setTag(1);
                    Log.d(TAG, "set tag to 1");
                    baServiceDUB.playSong();
                    Log.d(TAG, "song play'd");
                }

            }

        });
    //
    }
    private DUBAudioService baServiceDUB;

    private ServiceConnection serviceConnectionDUB = new ServiceConnection(){
        public void onServiceConnected(ComponentName className, IBinder baBinder) {
            baServiceDUB =
            ((DUBAudioService.DUBBackgroundAudioServiceBinder)baBinder).getService();
        }

        public void onServiceDisconnected(ComponentName className){
            baServiceDUB = null;
        }
//
    };

    void doBindService(){
        getApplicationContext().bindService(playbackServiceIntentDUB, serviceConnectionDUB,
                Context.BIND_AUTO_CREATE);
        Log.d(TAG, "do bind service");

    }

    @Override
    public void onResume() {
        getApplicationContext().bindService(playbackServiceIntentDUB, serviceConnectionDUB,
                Context.BIND_AUTO_CREATE);
            Log.d(TAG, "on resume + re-bound service");
        super.onResume();
    }

    @Override
    public void onDestroy(){
        stopService(playbackServiceIntentDUB);
        getApplicationContext().unbindService(serviceConnectionDUB);

        Log.d(TAG, "destroy'd + unbind service");
        //finish();
        super.onDestroy();
    }

}

Service Class:

public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{

Toast loadingMessage;

private static final String TAG = DUBAudioService.class.getSimpleName();

    public boolean isRunning;

    //to keep track of the playlist item
    Vector<PlaylistFile> playlistItems;

    MediaPlayer mediaPlayer;

    String baseURL = "";

    //keep track of which item from the vector we are on
    int currentPlaylistltemNumber = 0;

    public class DUBBackgroundAudioServiceBinder extends Binder {
        DUBAudioService getService() {
        return DUBAudioService.this;
        }
    }

    private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();



    @Override
    public IBinder onBind(Intent intent) {
        return basBinderDUB;
    }

    @Override
    public void onCreate() {
        Log.v("PLAYERSERVICE", "onCreate");
        mediaPlayer = new MediaPlayer();
        new MusicAsync().execute();
            Log.d(TAG, "execute'd async");
        mediaPlayer.setOnPreparedListener(this);
            Log.d(TAG, "set on prepared listener");
        mediaPlayer.setOnCompletionListener(this);
            Log.d(TAG, "set on completion listener");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //if (!mediaPlayer.isPlaying()) {
        //  mediaPlayer.start();
        //}
        return START_STICKY;
    }

    class MusicAsync extends AsyncTask<Void,Void,Void>{
        @Override
        protected void onPreExecute(){
        }
        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            //create empty vector 
            playlistItems = new Vector<PlaylistFile>();

            //HTTP client library
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here 

            Log.v("URI",getRequest.getURI().toString());

            try {
            HttpResponse httpResponse = httpClient.execute(getRequest);
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            // ERROR MESSAGE
            Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
            }
            else {
                InputStream inputStream = httpResponse.getEntity().getContent(); 
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = bufferedReader.readLine()) != null) { 
                    Log.v("PLAYLISTLINE","ORIG: " + line);

                    if (line.startsWith("#")) {
                        //Metadata
                        //Could do more with this but not fo now
                    } else if (line.length() > 0) {
                        String filePath = "";
                            if (line.startsWith("http://")) {
                            // Assume its a full URL 
                                filePath = line;
                            } else {
                            //Assume it’s relative
                            filePath = getRequest.getURI().resolve(line).toString();
                            }

                            PlaylistFile playlistFile = new PlaylistFile(filePath);
                            playlistItems.add (playlistFile);
                            }
                            }
                            inputStream.close();
                            }
                            } catch (ClientProtocolException e) { 
                                e.printStackTrace();
                            } catch (IOException e) {
                            e. printStackTrace();
                            }


                            currentPlaylistltemNumber = 0;
                            if (playlistItems.size() > 0)
                            {
                            String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
                            try {
                                mediaPlayer.setDataSource(path);

                            mediaPlayer.prepareAsync();}
                            catch (IllegalArgumentException e) 
                            { e.printStackTrace();
                            }catch (IllegalStateException e) { 
                                e.printStackTrace();
                            }catch (IOException e) {
                            e.printStackTrace();}
                            }



            return null;
        }
        //
        protected void onPostExecute(Void result){
            //playButton. setEnabled (false);
        }
    }



    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub

        super.onStart(intent, startId);
    }

    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            Log.d(TAG, "music stopp'd");
        }
        //mediaPlayer.release();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        // TODO Auto-generated method stub\
        Log.d(TAG, "music is prepared and will start");
        mediaPlayer.start();
    }

    public void onCompletion(MediaPlayer _mediaPlayer) {
        Log.d(TAG, "Song completed, next song");
        mediaPlayer.stop();
        mediaPlayer.reset();
            if (playlistItems.size() > currentPlaylistltemNumber + 1) { 
                currentPlaylistltemNumber++;
            String path =
                ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
                try {
                    mediaPlayer.setDataSource(path);
                    mediaPlayer.prepareAsync();
                } catch (IllegalArgumentException e) { 
                    e. printStackTrace();
                } catch (IllegalStateException e) { 
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }   
    }

    class PlaylistFile {
        String filePath;
            public PlaylistFile(String _filePath) {
                filePath = _filePath;
            }
            public void setFilePath(String _filePath) {
                filePath = _filePath;
            }
            public String getFilePath() {
                return filePath;
            }
        }


    public void playSong(){
        Log.d(TAG, "start'd");
        mediaPlayer.start();
    }

    public void pauseSong(){
        Log.d(TAG, "pause'd");
        mediaPlayer.pause();
    }



}

解决方案

I'd say you got lucky that it stopped -- only onPause() is guaranteed to be called when your Activity is backgrounded. The only time onDestroy() is called is when the system decides to reclaim the memory your app is using

The only guaranteed lifecycle calls are:

  • onCreate() only when the app is starting from scratch;
  • onResume() every run, whether paused or first created;
  • onPause() every time the system is moving your app to the background, period.

这篇关于Android-恢复服务的活动,并摧毁他们的毁灭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆