在服务中播放歌曲会使app UI变慢

时间:2017-03-27 13:03:29

标签: android performance service audio-player android-music-player

    public static final int MSG_FOREGROUND = 0;
    public static final int MSG_MAIN = 1;
    public static final int MSG_MAIN_OPEN = 2;
    public static final int MSG_CLOSE_SERVICE = 3;
    public static final int MSG_CHECK_PLAYING_STATUS = 4;
    public static final int MSG_PAUSE = 5;
    public static final int MSG_UPDATE_SEEKBAR = 6;
    public static final int MSG_SEEK = 7;
    public static final int MSG_REPEAT = 8;
    public static final int MSG_REPEAT_ON = 9;
    public static final int MSG_REPEAT_OFF = 10;
    public static final int MSG_SHUFFLE = 11;
    public static final int MSG_SHUFFLE_ON = 12;
    public static final int MSG_SHUFFLE_OFF = 13;
    public static final int MSG_CLOSE = 14;
    public static final int MSG_PLAY = 15;
    public static final int MSG_NEXT = 16;
    public static final int MSG_PREVIOUS = 17;
    public static final int MSG_CLOSE_AFTER_XMINUTES = 18;


    private static int duration;
    private static boolean isRunning = false;
    public static MediaPlayer player;


    private List<PlayerModel> songList;
    private int songPosition;
    private Bitmap notifyBackground;
    private String playerTitle, artistName;
    private int checkPlayStatus;
    private int seekPosition = 0;
    private boolean shuffle;
    private boolean isNotify = false;
    private boolean isRepeat;
    private Runnable milliSecRunnable = null;
    private boolean isVisibleStatus;

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

    private void sendMessageToUI(int actionStatus) {
        Message msg = Message.obtain(null, actionStatus);
        Message fragMsg = Message.obtain(null, actionStatus);
        if (AudioPlayerActivity.handler != null && msg != null)
            AudioPlayerActivity.handler.sendMessage(msg);
        if (FragmentAudioCards.messageHandler != null && fragMsg != null)
            FragmentAudioCards.messageHandler.sendMessage(fragMsg);
    }

    private void sendMessageToUINextPrev(int actionStatus) {
        Message msg = Message.obtain(null, actionStatus);
        Bundle mBundle = new Bundle();
        mBundle.putInt(getString(R.string.SONG_POSITION), songPosition);
        msg.setData(mBundle);
        Message fragMsg = Message.obtain(null, actionStatus);
        Bundle fragBundle = new Bundle();
        fragBundle.putInt(getString(R.string.SONG_POSITION), songPosition);
        fragMsg.setData(fragBundle);
        if (AudioPlayerActivity.handler != null && msg != null)
            AudioPlayerActivity.handler.sendMessage(msg);
        if (FragmentAudioCards.messageHandler != null && fragMsg != null)
            FragmentAudioCards.messageHandler.sendMessage(fragMsg);
    }

    private void sendMessageUpdateProgress(int actionStatus, long duration, long currDuration) {
        Message msg = Message.obtain(null, actionStatus);
        Bundle mBundle = new Bundle();
        mBundle.putLong(getString(R.string.SONG_DURATION), duration);
        mBundle.putLong(getString(R.string.SONG_CURR_DURATION), currDuration);
        msg.setData(mBundle);
        if (AudioPlayerActivity.handler != null && msg != null)
            AudioPlayerActivity.handler.sendMessage(msg);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        isRunning = false;
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        startPlayback(intentFilter);
    }

    private void showNotification() {
        RemoteViews views = new RemoteViews(getPackageName(),
                R.layout.status_bar);
        Intent intent = new Intent(this, MusicService.class);
        intent.setAction(String.valueOf(MSG_MAIN));
        PendingIntent pendingIntent = PendingIntent.getService(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent previousIntent = new Intent(this, MusicService.class);
        previousIntent.setAction(String.valueOf(MSG_PREVIOUS));
        PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                previousIntent, 0);
        Intent playIntent = new Intent(this, MusicService.class);
        playIntent.setAction(String.valueOf(MSG_CHECK_PLAYING_STATUS));
        PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent nextIntent = new Intent(this, MusicService.class);
        nextIntent.setAction(String.valueOf(MSG_NEXT));
        PendingIntent pnextIntent = PendingIntent.getService(this, 0,
                nextIntent, 0);
        Intent closeIntent = new Intent(this, MusicService.class);
        closeIntent.setAction(String.valueOf(MSG_CLOSE));
        PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
                closeIntent, 0);
        android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_play_white_24dp)
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentIntent(pendingIntent)
                .setContent(views);
        views.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent);
        views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
        views.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent);
        views.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent);
        views.setImageViewResource(R.id.status_bar_play,
                checkPlayStatus);
        views.setImageViewBitmap(R.id.status_bar_album_art,
                notifyBackground);
        views.setTextViewText(R.id.status_bar_track_name, playerTitle);
        views.setTextViewText(R.id.status_bar_artist_name, artistName);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        startForeground(1, builder.build());
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null)
            if (intent.getAction().equals(String.valueOf(MSG_FOREGROUND))) {
                isRunning = true;
                songList = LaHolder.getInstance().retrieve(getString(R.string.audio_list));
                songPosition = intent.getIntExtra(getString(R.string.SONG_POSITION), 0);
                boolean isMiniPlayer = intent.getBooleanExtra(getString(R.string.mini_player), false);
                isVisibleStatus = intent.getBooleanExtra(getString(R.string.visible_status), true);
                SharedPreferences prefs = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE);
                if (prefs.getBoolean(getString(R.string.VISIBLE_PLAYER), false)) {
                    seekPosition = intent.getIntExtra(getString(R.string.CURRENT_POSITION), 0);
                    final SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putBoolean(getString(R.string.VISIBLE_PLAYER), false);
                    editor.commit();
                } else
                    seekPosition = 0;

                if (!isMiniPlayer)
                    playSong();
                if (isVisibleStatus) {
                    checkPlayStatus = R.drawable.ic_pause_white_24dp;
                    go();
                    sendMessageToUI(MSG_PLAY);
                } else {
                    checkPlayStatus = R.drawable.ic_play_white_24dp;
                    pausePlayer();
                    sendMessageToUI(MSG_PAUSE);
                }
                showNotification();

            } else if (intent.getAction().equals(String.valueOf(MSG_CHECK_PLAYING_STATUS))) {
                if (player.isPlaying()) {
                    checkPlayStatus = R.drawable.ic_play_white_24dp;
                    showNotification();
                    pausePlayer();
                    sendMessageToUI(MSG_PAUSE);

                } else {
                    checkPlayStatus = R.drawable.ic_pause_white_24dp;
                    showNotification();
                    go();
                    sendMessageToUI(MSG_PLAY);

                }
            } else if (intent.getAction().equals(String.valueOf(MSG_NEXT))) {
                playNext();
                checkPlayStatus = R.drawable.ic_pause_white_24dp;
                if (AudioPlayerActivity.handler == null) {
                    seekPosition = 0;
                    playSong();
                    SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putString(getString(R.string.visible_song_title), songList.get(songPosition).getPlayerTitle());
                    editor.putString(getString(R.string.visible_song_artist), songList.get(songPosition).getPlayerArtist());
                    editor.putString(getString(R.string.visible_album_id), String.valueOf(songList.get(songPosition).getPlayerId()));
                    editor.commit();
                }
                sendMessageToUINextPrev(MSG_NEXT);
                showNotification();
            } else if (intent.getAction().equals(String.valueOf(MSG_PREVIOUS))) {
                playPrev();
                if (AudioPlayerActivity.handler == null) {
                    seekPosition = 0;
                    SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putString(getString(R.string.visible_song_title), songList.get(songPosition).getPlayerTitle());
                    editor.putString(getString(R.string.visible_song_artist), songList.get(songPosition).getPlayerArtist());
                    editor.putString(getString(R.string.visible_album_id), String.valueOf(songList.get(songPosition).getPlayerId()));
                    editor.commit();
                    playSong();
                }
                sendMessageToUINextPrev(MSG_PREVIOUS);
                checkPlayStatus = R.drawable.ic_pause_white_24dp;
                showNotification();
            } else if (intent.getAction().equals(String.valueOf(MSG_SEEK))) {
                seek(intent.getIntExtra(getString(R.string.SEEK_POSITION), 0));
            } else if (intent.getAction().equals(String.valueOf(MSG_UPDATE_SEEKBAR))) {
                sendMessageUpdateProgress(MSG_UPDATE_SEEKBAR, getDur(), getPosn());
            } else if (intent.getAction().equals(String.valueOf(MSG_REPEAT))) {
                isRepeat = intent.getBooleanExtra(getString(R.string.repeat_status), false);
                if (isRepeat) {
                    sendMessageToUI(MSG_REPEAT_OFF);
                    isRepeat = false;
                } else {
                    sendMessageToUI(MSG_REPEAT_ON);
                    isRepeat = true;
                }
            } else if (intent.getAction().equals(String.valueOf(MSG_SHUFFLE))) {
                shuffle = intent.getBooleanExtra(getString(R.string.shuffle_status), false);
                if (shuffle) {
                    sendMessageToUI(MSG_SHUFFLE_OFF);
                } else {
                    sendMessageToUI(MSG_SHUFFLE_ON);
                }
            } else if (intent.getAction().equals(String.valueOf(MSG_CLOSE))) {
                sendMessageToUI(MSG_CLOSE);
                final SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putInt(getString(R.string.visible_current_position), player.getCurrentPosition());
                editor.commit();
                stopSelf();
                Intent broadcastIntent = new Intent(MultHomePageActivity.BROADCAST_ACTION);
                sendBroadcast(broadcastIntent);
                stopPlayback();
            } else if (intent.getAction().equals(String.valueOf(MSG_CLOSE_SERVICE))) {
                final SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                editor.putInt(getString(R.string.visible_current_position), player.getCurrentPosition());
                editor.commit();
                stopSelf();
                stopPlayback();
            } else if (intent.getAction().equals(String.valueOf(MSG_MAIN))) {
                Intent audioPlayerIntent = new Intent(this, AudioPlayerActivity.class);
                audioPlayerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
                audioPlayerIntent.putExtra(this.getString(R.string.SONG_POSITION), songPosition);
                audioPlayerIntent.putExtra(getString(R.string.from_notification), true);
                audioPlayerIntent.putExtra(getString(R.string.mini_player), true);
                audioPlayerIntent.putExtra(getString(R.string.visible_status),
                        checkPlayStatus == R.drawable.ic_pause_white_24dp);
                startActivity(audioPlayerIntent);
            } else if (intent.getAction().equals(String.valueOf(MSG_MAIN_OPEN))) {
                Intent audioPlayerIntent = new Intent(this, AudioPlayerActivity.class);
                audioPlayerIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                audioPlayerIntent.putExtra(this.getString(R.string.SONG_POSITION), intent.getIntExtra(
                        getString(R.string.SONG_POSITION), 0));
                audioPlayerIntent.putExtra(getString(R.string.mini_player),
                        intent.getBooleanExtra(getString(R.string.mini_player), false));
                audioPlayerIntent.putExtra(getString(R.string.CURRENT_POSITION),
                        intent.getIntExtra(getString(R.string.CURRENT_POSITION), 0));
                audioPlayerIntent.putExtra(getString(R.string.visible_status),
                        intent.getBooleanExtra(getString(R.string.visible_status), false));
                startActivity(audioPlayerIntent);
            } else if (intent.getAction().equals(String.valueOf(MSG_CLOSE_AFTER_XMINUTES))) {
                Handler handler = new Handler();
                Long milliSec = intent.getLongExtra(getString(R.string.X_MINUTES), 0);
                if (milliSec != 0) {
                    milliSecRunnable = new Runnable() {
                        @Override
                        public void run() {
                            sendMessageToUI(MSG_CLOSE);
                            final SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                            editor.putInt(getString(R.string.visible_current_position), player.getCurrentPosition());
                            editor.commit();
                            stopSelf();
                            Intent broadcastIntent = new Intent(MultHomePageActivity.BROADCAST_ACTION);
                            sendBroadcast(broadcastIntent);
                        }
                    };
                    handler.postDelayed(milliSecRunnable, milliSec);
                } else {

                    handler.removeCallbacks(milliSecRunnable);

                }
                stopPlayback();

            }
        return START_STICKY;
    }

    public static boolean isRunning() {
        return isRunning;
    }

    private void pausePlayer() {
        if (player.isPlaying()) {
            duration = player.getDuration();
            player.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Timer timer = new Timer();
        sendMessageToUI(MusicService.MSG_CLOSE);
        if (timer != null) {
            timer.cancel();
        }
        player.stop();
        player.release();
        player = null;
        isRunning = false;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        player.stop();
        player.release();
        return false;
    }

    public static int getPosn() {
        return player.getCurrentPosition();
    }

    public static int getDur() {
        return duration;
    }

    private void seek(int posn) {
        player.seekTo(posn);
    }

    private void go() {
        if (!player.isPlaying()) {
            duration = player.getDuration();
            player.start();
        }
    }

    private void playPrev() {
        songPosition--;
        if (songPosition < 0) songPosition = songList.size() - 1;

    }

    private void playSong() {
        player.reset();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        PlayerModel playSong = songList.get(songPosition);
        playerTitle = playSong.getPlayerTitle();
        artistName = playSong.getPlayerArtist();
        notifyBackground = Constants.getDefaultAlbumArt(getApplicationContext(), playSong.getPlayerAlbumId());
        try {
            player.setDataSource(playSong.getPlayerData());
        } catch (Exception ignored) {
        }
        try {
            player.prepare();
            if (player != null) {
                player.seekTo(seekPosition);
            }
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (isVisibleStatus && !mp.isPlaying())
                        mp.start();
                    else {
                        duration = mp.getDuration();

                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        SQLiteAdapter mySQLiteAdapter = new SQLiteAdapter(getApplicationContext());
        mySQLiteAdapter.openToWrite();
        PlayerModel playerModel = songList.get(songPosition);
        mySQLiteAdapter.insertRecentAudios(playerModel.getPlayerId(),
                playerModel.getPlayerName(),
                playerModel.getPlayerDuration(),
                playerModel.getPlayerAlbum(),
                playerModel.getPlayerAlbumId(),
                playerModel.getPlayerArtist(),
                playerModel.getPlayerData(),
                playerModel.getPlayerTitle(),
                Utility.getDateTime());
        mySQLiteAdapter.close();

    }

    private void playNext() {
        if (shuffle) {
            Random rand = new Random();
            int newSong = songPosition;
            while (newSong == songPosition) {
                newSong = rand.nextInt(songList.size());
            }
            songPosition = newSong;
        } else {
            songPosition++;
            if (songList != null)
                if (songPosition >= songList.size()) songPosition = 0;
        }

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (isRepeat) {
            checkPlayStatus = R.drawable.ic_pause_white_24dp;
            playSong();
            sendMessageToUI(MSG_PLAY);
            showNotification();
        } else {
            if (songList != null) {
                playNext();
                if (AudioPlayerActivity.handler == null) {
                    seekPosition = 0;
                    SharedPreferences.Editor editor = getSharedPreferences(AppConstants.LA_PREFS_NAME, MODE_PRIVATE).edit();
                    editor.putString(getString(R.string.visible_song_title), songList.get(songPosition).getPlayerTitle());
                    editor.putString(getString(R.string.visible_song_artist), songList.get(songPosition).getPlayerArtist());
                    editor.putString(getString(R.string.visible_album_id), String.valueOf(songList.get(songPosition).getPlayerId()));
                    editor.commit();
                    playSong();
                }
                sendMessageToUINextPrev(MSG_NEXT);
                checkPlayStatus = R.drawable.ic_pause_white_24dp;
                playSong();
                showNotification();

            }

        }
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        if (player != null) {
            if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                if (!player.isPlaying()) {
                    if (isNotify) {
                        checkPlayStatus = R.drawable.ic_pause_white_24dp;
                        showNotification();
                        go();
                        sendMessageToUI(MSG_PLAY);
                    }
                }

            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                if (player.isPlaying()) {
                    checkPlayStatus = R.drawable.ic_play_white_24dp;
                    showNotification();
                    isNotify = true;
                    pausePlayer();
                    sendMessageToUI(MSG_PAUSE);
                }
            }
        }
    }

    private void startPlayback(IntentFilter intentFilter) {
        registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
    }

    private void stopPlayback() {
        try {
            unregisterReceiver(myNoisyAudioStreamReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    private BroadcastReceiver myNoisyAudioStreamReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
                checkPlayStatus = R.drawable.ic_play_white_24dp;
                showNotification();
                isNotify = true;
                pausePlayer();
                sendMessageToUI(MSG_PAUSE);
            }
        }


    };
}

我正在开发一个音乐应用程序。在后台使用服务播放歌曲。当我完全播放歌曲超过一个小时使我的应用程序UI变慢。媒体播放器没有问题,歌曲播放正常.app ui started落后很多。有人给我一个soln pls?

0 个答案:

没有答案