ȸ¿ø°¡ÀԡžÆÀ̵ð/ºñ¹øã±â
ȨÀ¸·Î

Service µî·ÏÇϱâ
7³â Àü
Android App¿¡¼­ Service¸¦ ¸¸µé¶§

AndroidManifest.xml  ¿¡ Service class¸¦ µî·Ï ÇÑ´Ù.
<application>
.....
          <service android:name="UsbPlayerService" android:enabled="true">
              <category android:name="android.intent.category.DEFAULT" />
          </service>
</application>

Java source¿¡¼­ service¸¦ »ó¼Ó¹Þ¾Æ¼­ class¸¦ »ý¼ºÇÏ¸é µÈ´Ù.
package com.pinkrabbit.pinkusbplayer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by pinkrabbit on 2015-12-21.
*/
public class UsbPlayerService extends Service {
    static MediaPlayer mPlayer = null;
    private BroadcastReceiver mUnmountReceiver = null;
    private String MYTAG = "UsbPlayerService";
    private String PROR_STARTPAY = "pinkrabbit.play";
    private Boolean looping = true;
    public Boolean isLive = false;
    private AudioManager audio;
    private static boolean externalStorageReadable = false;
    public Uri before_songUri ;
    private ArrayList<Song> songList;
    private Context context ;
    public boolean threadRunLive  = false;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
       // Log.d(MYTAG, "Start service onCreate()");
        songList = new ArrayList<Song>();
        System.setProperty(PROR_STARTPAY, "true");
        String test = System.getProperty(PROR_STARTPAY);
        Log.e(MYTAG, "get property " + test);
       // audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
       // audio.setStreamVolume(AudioManager.STREAM_MUSIC, 6, 0);
        context=getApplicationContext();
        new Thread(new Runnable(){
            public void run(){
                new Thread(checkproperty).start();
        registerExternalStorageListener();
    }
        }).start();
    }
    @Override
    public void onDestroy() {
        Log.d(MYTAG, " o£îDestroy()");
        if (mPlayer != null) {
                mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        super.onDestroy();
    }

    public void startPlay(Integer Index) throws IOException {
        if(mPlayer != null) {
            Log.d(MYTAG, "startPlay() is playing....");
            return;
        }
        Log.d(MYTAG, "startPlay()");
        isLive =true;
        if (songList.isEmpty()) {
            Log.e(MYTAG, "not found song list");
            return;
        }

        Uri songUri = Uri.withAppendedPath(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "" + songList.get(Index).getID());

        if(songUri == null) return;
        Log.d(MYTAG, "songUri : " + songUri);
        try {
            mPlayer = new MediaPlayer();
            mPlayer.reset();
            mPlayer.setDataSource(this, songUri);
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //SystemClock.sleep(50);
                    {
                        mPlayer.stop();
                    mPlayer.release();
                    mPlayer = null;
                }
                }
            });
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            SystemClock.sleep(1);
            mPlayer.prepare();
            SystemClock.sleep(1);
            mPlayer.start();
            Log.w(MYTAG, "play track");
        } catch (IllegalStateException e) {
            e.printStackTrace();
            Log.w(MYTAG, "Unable to play track");
        } catch (IOException e) {
            e.printStackTrace();
            Log.w(MYTAG, "Unable to play track");
        }

    }
    public void registerExternalStorageListener() {
        if (mUnmountReceiver == null) {
            mUnmountReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
                        Log.d(MYTAG, " o£îReceive : ACTION_MEDIA_EJECT");
                        System.setProperty(PROR_STARTPAY, "false");
                        if (!songList.isEmpty()) {
                            songList.clear();
                        }
                        if (mPlayer == null) {
                            return;
                        } else {
                            //Log.d(MYTAG, " o£îReceive : is mPlayer null?? ");
                                Log.d(MYTAG, " o£îReceive : stop");
                                mPlayer.stop();
                            mPlayer.release();
                            mPlayer = null;
                        }
                    }else if(action.equals(Intent.ACTION_MEDIA_MOUNTED)){
                        System.setProperty(PROR_STARTPAY, "true");
                    } else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
                        Log.d(MYTAG, " o£îReceive : ACTION_MEDIA_SCANNER_FINISHED");
                        externalStorageReadable = false;
                        if(!songList.isEmpty()) {
                            songList.clear();
                        getSongList();
                        }
                        if (!songList.isEmpty()) {
                            //sort alphabetically by title
                            Collections.sort(songList, new Comparator<Song>() {
                                public int compare(Song a, Song b) {
                                    return a.getTitle().compareTo(b.getTitle());
                                }
                            });
                           // new Thread(checnkproperty);
                          //  new Thread(run).start();
                        }
                    }
                }
            };
            checkStorage();
            if (externalStorageReadable == true) {
                Log.d(MYTAG, "externalStorageReadable  true");
                externalStorageReadable = false;
                //getSongList();
                if (songList.size() != 0) {
                    //sort alphabetically by title
                    Collections.sort(songList, new Comparator<Song>() {
                        public int compare(Song a, Song b) {
                            return a.getTitle().compareTo(b.getTitle());
                        }
                    });
                  //  new Thread(run).start();
                  //  Log.d(MYTAG, "Thread(run).start");
                }
            }
            IntentFilter iFilter = new IntentFilter();
            iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
            iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
            iFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
            iFilter.addDataScheme("file");
            registerReceiver(mUnmountReceiver, iFilter);
        }
    }
    public Runnable checkproperty =new Runnable() {
        @Override
        public void run() {
            do{
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String status = System.getProperty(PROR_STARTPAY);
                //Log.d(MYTAG,"getprop "+ status);
                if(status.equals("true"))
                {
                    if(!songList.isEmpty() && mPlayer == null && isLive == false &&  threadRunLive == false ) {
                        //Log.d("MYTAG, "start play thread");
                        new Thread(run).start();
                    }else {
;                       if(songList.isEmpty()) {
                          //  Log.d(MYTAG,"checkProperty sonList Empty ");
                            getSongList();
                        }
                    }
                    //registerExternalStorageListener();
                }else if(status.equals("false")){
                 //   Log.d(MYTAG,"checkProperty getprop "+ status);
                    isLive = false;
                    //TODO excption occure
                    if(mPlayer != null) {
                        mPlayer.stop();
                    mPlayer.release();
                    mPlayer = null;
                    }
                }
            }while (true);
        }
    };
    public Runnable run = new Runnable() {
        @Override
        public void run() {
            do {
                if (songList.isEmpty()) break;
                Integer playcount = songList.size();
                do {
                    threadRunLive = true;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (songList.isEmpty()) {
                        //Log.d(MYTAG, "RUN  thread bye : song list empty");
                        threadRunLive = false;
                        break;
                    }
                    if (mPlayer == null) {
                        playcount -= 1;
                       // Log.d(MYTAG, "RUN :songList.size :" + songList.size() + " playcount :" + playcount);
                        try {
                            if(mPlayer != null && mPlayer.isPlaying()) {
                                Log.d(MYTAG, "RUN :already playing...");
                            } else {
                            startPlay(playcount);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(isLive == false) {
                        threadRunLive = false;
                        Log.d(MYTAG, "RUN  thread bye");
                        return;
                    }
                } while (playcount > 0);
            } while (looping);// list looping
            threadRunLive = false;
        }
    };

    //method to retrieve song info from device
    public void getSongList() {
      //  Log.d(MYTAG, "getSongList ");
        String[] projection = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore
                .Audio.Media.ARTIST};
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
        //query external audio
        ContentResolver musicResolver = getContentResolver();
        Cursor musicCursor = musicResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null, null);
        //iterate over results if valid
        if (musicCursor == null) {
            Log.e(MYTAG, "getSongList musicCursor is null");
            return;
        }
        if (musicCursor != null && musicCursor.moveToFirst()) {
            //get columns
            int titleColumn = musicCursor.getColumnIndex
                    (MediaStore.Audio.Media.TITLE);
            int idColumn = musicCursor.getColumnIndex
                    (MediaStore.Audio.Media._ID);
            int artistColumn = musicCursor.getColumnIndex
                    (MediaStore.Audio.Media.ARTIST);
            //add songs to list
            do {
                long thisId = musicCursor.getLong(idColumn);
                Uri IdToUri = Uri.withAppendedPath(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "" + thisId);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisfilePath = getFilePathFromContentUri(IdToUri, musicResolver);
                if(thisfilePath.contains("/storage/usb0/")) {
                   //  Log.d(MYTAG, "IdToUri : " + IdToUri + "file_path"+ thisfilePath);
                    songList.add(new Song(thisId, thisTitle, thisfilePath));
                }
            }
            while (musicCursor.moveToNext());
        }
        musicCursor.close();
    }
    private String getFilePathFromContentUri(Uri selectedVideoUri, ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};
        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }
    private static void checkStorage() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            externalStorageReadable = true;
        } else {
            externalStorageReadable = false;
        }
    }
}
ÃßõÃßõ : 562 Ãßõ ¸ñ·Ï
¹øÈ£ Á¦¸ñ
1,286
[Android] webview ssl ¹®Á¦
1,285
[Android] Webview url ¼û±â±â
1,284
[Android] AlarmManager ÀÏÁ¤½Ã°£ À̺¥Æ® ½ÇÇà
1,283
¾Èµå·ÎÀÌµå ¿ÀǼҽº ³¡ÆÇ
1,282
android studio DefaultHttpClient, HttpClient import ¿¡·¯
1,281
[Android] Webview ¸Þ¼Òµå
1,280
¾Èµå·ÎÀ̵å: ¼­ºñ½º Service ¿¹Á¦
1,279
[Android] Effect (¿Àµð¿À¸ðµå) º§¸ðµå, Áøµ¿¸ðµå, ¹«À½¸ðµå½Ã µ¿ÀÛó¸®
1,278
Mediaplayer ·Î ÁöÁ¤µÇ¾îÀÖ´Â º§¼Ò¸® Àç»ýÇϱâ
1,277
Android Intent - ¾Èµå·ÎÀ̵å ÀÎÅÙÆ®
1,276
[Android Intent Useage] ¾Èµå·ÎÀ̵å Intent »ç¿ë ¹æ¹ý
1,275
SharedPreferences¶õ?
1,274
ÀÎÅÙÆ®(Intent)·Î µ¥ÀÌÅÍ Àü´Þ(putExtra, getExtras)
1,273
¾Èµå·ÎÀÌµå ±¸±Û ¾Öµå¸÷ Àü¸é±¤°í ³Ö±â
1,272
¾Èµå·ÎÀÌµå µÚ·Î°¡±â ¹öÆ° ´õºíŬ¸¯Çؼ­ ¾Û Á¾·áÇϱâ
1,271
¾Ë¸²Ã¢ ¶ç¿ì±â(Multi Choice, Single Choice)
1,270
Android SharedPreferences »ç¿ë ¿¹Á¦
1,269
¾Èµå·ÎÀ̵å PHP GET ¹æ½Ä Åë½Å¿¡¼­ ÇÑ±Û ±úÁü(?) ÇØ°á
1,268
¾Èµå·ÎÀÌµå ¾Û ÃÖÃÊ ½ÇÇà½Ã ¹ÙÅÁÈ­¸é¿¡ ¾ÆÀÌÄÜ(Shortcut) »ý¼ºÇϱâ
1,267
ÇöÀç½Ã°£(Local Time) °¡Á®¿À±â
1,266
ÆÄÀÏ »ý¼º ¹× ÀúÀå
1,265
µÚ·Î°¡±â(Back ¹öÆ°) µÎ¹ø ´­·¯ ¾Û Á¾·áÇϱâ
1,264
Custom ListView (Ä¿½ºÅÒ ¸®½ºÆ®ºä) Footer¸¦ ÀÌ¿ëÇÑ ´õº¸±â ±¸Çö
1,263
CheckBox(üũ¹Ú½º) À̹ÌÁö º¯°æÇϱâ
1,262
C¼­¹ö¿Í ¼ÒÄÏÅë½Å
1,261
½½¶óÀ̵ù ¸Þ´º - SimpleSideDrawer
1,260
selector·Î ¹öÆ° ¾×¼Ç À̹ÌÁö º¯°æ
1,259
À̹ÌÁö¹öÆ° »çÀÌÁî Á¶Àý
1,258
XmlPullParser °£´ÜÇÑ »ç¿ë¹ý
1,257
¹öÆ°»çÀÌ ¿©¹é ¾ø¾Ö±â
¸ñ·Ï
¹ÂÁ÷Æ®·ÎÆ® ºÎ»ê±¤¿ª½Ã ºÎ»êÁø±¸ °¡¾ßµ¿ ¤Ó °³ÀÎÁ¤º¸Ãë±Þ¹æħ
Copyright ¨Ï musictrot All rights reserved.