# Performancevervesserungen: Ideen?



## Lucaaa (7. Feb 2019)

Hallo!
Ich habe eine Service Klasse  die Einen Musikplayer verwaltet. Das Problem ist, das der Service so knapp 30% CPU frisst, und den RAM immer weiter füllt (Und die Ladezeiten sind auch nicht grade kurz) Hat jemand eine Idee, wie ich das ganze verbessern kann?

Hier der Code:

```
package com.ludevstudio.mp3audiobookplayer.services;


import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Switch;

import com.ludevstudio.mp3audiobookplayer.data.AudioFile;
import com.ludevstudio.mp3audiobookplayer.data.Book;
import com.ludevstudio.mp3audiobookplayer.data.Library;

import java.io.File;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

public class MediaPlayerService extends Service {

    public Notification notification;
    NotificationCompat.Builder notificationBuilder;
    RemoteViews.RemoteView sNotificationView;
    MediaPlayer player;

    Timer progressTimer;
    Thread progressThread;
    Thread workerThread;

    Book book;
    AudioFile[] chapters;
    Library library;


    @Override
    public void onCreate() {
        super.onCreate();
        library =new Library();

          }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
    workerThread =new Thread(new Runnable() {
        @Override
            public void run() {


// if service is starting fi4rst time

       if(book==null || player==null || chapters==null) {
            // get book
            if(intent.getParcelableExtra("book")!=null) {
                book = intent.getParcelableExtra("book");
            }
            // set chapters

           loadBookChapters();

            // init player
            initPlayer();

        }

        String cmd = intent.getAction();
            Log.d("logdata111", "switch statement");
        switch(cmd) {
            case Action.ACTION_PLAY :
            play();
            sendStats();
            startSendingProgress();
            break;

            case Action.ACTION_PAUSE :
                pause();
                break;

            case Action.ACTION_STARTSENDINGPROGRESS :
                progressTimer.cancel();
                progressThread.interrupt();
                startSendingProgress();
                break;
            case Action.ACTION_STOPSENDINGPROGRESS :
                progressTimer.cancel();
                progressThread.interrupt();
                break;
            case  Action.ACTION_CHANGEPLAYMODE :
                if(player.isPlaying()) {
                    pause();
                } else {
                    play();
                }
                sendStats();
                break;
            case Action.ACTION_SHUTDOWN :
                onDestroy();
                break;
        }
            sendStats();
        }
    });
        workerThread.start();
            return START_NOT_STICKY;
         }

        private void play() {
            if(!player.isPlaying()) {
               player.seekTo((int)book.getCurrentChapterprogress());
                player.start();
                startSendingProgress();
            }
        }

        private void pause() {
        player.pause();
        stopSendingProgress();
        updateBook(true);}

        private void loadBookChapters() {
            long start = System.currentTimeMillis();
            File[] cFilesTmp = library.getChaptersOfBook(new File(book.getPath()));

            chapters = new AudioFile[cFilesTmp.length];
           chapters[book.getCurrentChapter()-1] =new AudioFile(cFilesTmp[book.getCurrentChapter()-1]);
            chapters[book.getCurrentChapter()] =new AudioFile(cFilesTmp[book.getCurrentChapter()]);

          new Thread(new Runnable() {
              @Override
              public void run() {
                  for(int i =0; i< cFilesTmp.length; i++) {
                      if(chapters[i]!=null)
                          chapters[i] =new AudioFile(cFilesTmp[i]);
                  }
              }
          }).start();

        }

        private void nextChapter() {
            if (book.getCurrentChapter()<book.getChapters()) {
                 book.setCurrentChapterprogress(0);
                book.setCurrentChapter(book.getCurrentChapter() + 1);
                updateBook(false);
                updatePlayer();
                play();
            } else {
                book.setCurrentChapter(1);
                book.setCurrentChapterprogress(0);
                updateBook(false);
                updatePlayer();
            }
            sendStats();
        }


        private void updatePlayer() {
            player.release();
            player = MediaPlayer.create(this, Uri.parse(chapters[book.getCurrentChapter()-1].getPath()));
        }

        private void updateBook(boolean shouldGetProgressFromPlayer) {
        if(shouldGetProgressFromPlayer)
        book.setCurrentChapterprogress(player.getCurrentPosition());
        book.setCurrentProgress(library.calcCurrentBookProgress(book));

        Intent intent =new Intent(this, DataBaseService.class);
        intent.putExtra("book", book);
        intent.setAction(DataBaseService.ACTION.ACTION_SAVE_BOOK);
        startService(intent);
        }

        private void initPlayer() {
            player = MediaPlayer.create(this, Uri.parse(chapters[book.getCurrentChapter()-1].getPath()));
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    nextChapter();
                }
            });
    }

    private void startSendingProgress() {
       progressThread =new Thread(new Runnable() {
           @Override
           public void run() {

        progressTimer =new Timer("progresstimer");
        long delay = 1000;
        TimerTask task =new TimerTask() {
            @Override
            public void run() {
                Intent status =new Intent("progress");
                status.putExtra(Status.STATUS_PROGRESS, player.getCurrentPosition());
                LocalBroadcastManager.getInstance(MediaPlayerService.this).sendBroadcast(status);

            }
        };
        progressTimer.schedule(task, 0, delay);
           }
       });
       progressThread.start();

    }


    private void stopSendingProgress() {
       progressTimer.cancel();
        progressThread.interrupt();
    }

    private void sendStats() {
        Bundle statusData =new Bundle();
        statusData.putString(Status.STATUS_TITLE, book.getTitle());
        statusData.putLong(Status.STATUS_ID, book.getID());
        statusData.putInt(Status.STATUS_CHAPTERS, book.getChapters());
        statusData.putInt(Status.STATUS_CURRENTCHAPTER, book.getCurrentChapter());
        statusData.putLong(Status.STATUS_DURATION, book.getDuration());
        statusData.putBoolean(Status.STATUS_ISPLAYING, player.isPlaying());
        statusData.putInt(Status.STATUS_PROGRESS, player.getCurrentPosition());
        Intent status = new Intent("stats");
        status.putExtra("statusdata", statusData);
        LocalBroadcastManager.getInstance(this).sendBroadcast(status);
        updateBook(true);
    }

    @Override
    public void onDestroy() {
        player.stop();
        new Thread(new Runnable() {
            @Override
            public void run() {
                updateBook(true);

            }
        }).start();

         progressThread.interrupt();
        progressTimer.cancel();
        workerThread.interrupt();
        super.onDestroy();

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        onDestroy();
    }

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


    public interface Action {
        public static final String ACTION_PLAY = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.play";
        public static final String ACTION_PAUSE = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.pause";
        public static final String ACTION_STARTSENDINGPROGRESS = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.startsendingprogress";
        public static final String ACTION_STOPSENDINGPROGRESS = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.stopstendingprogress";
        public static final String ACTION_CHANGEPLAYMODE = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.changeplaymode";
        public static final String ACTION_SHUTDOWN = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.action.shutdown";
    }

    public interface Status {
        public static final String STATUS_TITLE = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.title";
        public static final String STATUS_CURRENTCHAPTER = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.chapterprogress";
        public static final String STATUS_CHAPTERS = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.chapters";
        public static final String STATUS_DURATION = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.duration";
        public static final String STATUS_ID = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.id";
        public static final String STATUS_PROGRESS = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.progress";
        public static final String STATUS_ISPLAYING = "com.ludevstudio.mp3audiobookplayer.services.mediaplayerservice.status.isplaying";
         }
}
```


----------

