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

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,226
android | ²¨Áø È­¸é¿¡¼­ ¾Û ½ÇÇàÇϱâ / Àáµç È­¸é ±ú¿ì±â / Àá±Ý È­¸é À§·Î ½ÇÇà/
1,225
android ÇöÀç WebView¿¡¼­ ¿ÜºÎ ÆäÀÌÁö ºÒ·¯¿À±â / WebView »õâ ¶ç¿ìÁö ¾Ê±â / WebViewClient
1,224
Activity ¸¦ dialog style·Î ¸¸µé±â
1,223
webview ¾Æ·¡ button ³Ö±â
1,222
webview scroll ±â´É ¸·±â(touch´Â µÊ)
Service µî·ÏÇϱâ
1,220
booting ÈÄ¿¡ ÀÚµ¿À¸·Î ½ÇÇà µÇ´Â app ¸¸µé±â
1,219
[Android] Intent È°¿ë ¿¹½Ã
1,218
Android ¼³Ä¡µÈ ¾îÇà ¸ñ·Ï PackageInfo¸¦ ÅëÇØ °¡Á®¿À±â ¹× ´Ù¸¥ ¾îÇà ½ÇÇà
1,217
[ANDROID(¾Èµå·ÎÀ̵å) ¾Û °³¹ß ±âÃÊ] MEDIAPLAYER À½¾Ç Àç»ýÇϱâ
1,216
[¾Èµå·ÎÀ̵å] ¿ÜºÎ ¾Û ½ÇÇà
1,215
¾Èµå·ÎÀÌµå ¼º´ÉÀ» À§ÇÑ ¼³°è
1,214
ÆÄÀÏ ¾÷·Îµå ¹× ÆĶó¸ÞÅÍ Àü¼Û (sending file & parameters by MultipartEntity / post)
1,213
MediaPlayer °¡·ÎÀÏ ¶§ UI ¼û±â°í Ç®½ºÅ©¸° ¸¸µé±â
1,212
À¥ºä¿¡¼­ html ÅÂ±× ¾ø¾Ö´Â ¹ý(Remove the html tag on loading web page in WebView)
1,211
´Ù¸¥ ¾Û ½ÇÇàÇϰųª Ç÷¹ÀÌ ½ºÅä¾î·Î À̵¿(Launch another app by code)
1,210
À¥ ºä¿¡¼­ ÅÂ±× Á¤º¸ ÃàÃâÇϱâ(Get the information of html tag in WebView of android)
1,209
ÀÚµ¿À¸·Î ¿¡µðÆ®ºä¿¡ Æ÷Ä¿½º µÇ´Â °Í ¸·±â
1,208
addJavascriptInterface ¿À·ù(Android WebView.addJavascriptInterface not Working)
1,207
Ä¿½ºÅÒ Å佺Ʈ ¶ç¿ì±â(To show Custom Toast)
1,206
À¥¿¡¼­ ÆÄÀÏ »çÀÌÁî¿Í ÄÜÅÙÆ®(ÄÁÅÙÃ÷) ŸÀÔ ¾Ë¾Æº¸´Â »ùÇÃÄÚµå
1,205
¾Èµå·ÎÀ̵å ÅؽºÆ® ºä¿¡¼­ Áö¿øÇÏ´Â HTML ű׵é
1,204
ÀÎÅÍ³Ý ÁÖ¼Ò À¯È¿¼º °Ë»ç (regular expression for url)
1,203
SpannableStringÀ¸·Î ÅؽºÆ® ºä¿¡ ¾ÆÀÌÄÜ ³Ö´Â ¹ý
1,202
½ÇÇà°¡´ÉÇÑ ¾Û ¸ñ·Ï (Get launchable apps in android)
1,201
HTMLÀ» ¾Èµå·ÎÀ̵å À¥ºä¿¡ ¸ðµÎ º¸ÀÌ°Ô Çϱâ Using WebView ViewPort in android
1,200
so ÆÄÀÏ ¾Èµå·ÎÀÌµå ½ºÆ©µð¿À¿¡¼­ »ç¿ëÇÏ´Â ¹ý
1,199
[¾Èµå·ÎÀ̵å] È­¸é »çÀÌÁî ±¸Çϱâ
1,198
[¾Èµå·ÎÀ̵å] ¾Èµå·ÎÀÌµå ½ºÆ©µð¿À¿¡¼­ ºôµå ÆÄÀÏ À̸§ ¼öÁ¤Çϱâ.
1,197
¿ÜºÎ ¾Û ½ÇÇà½ÃÅ°±â (launch external app in android)
¸ñ·Ï
¹ÂÁ÷Æ®·ÎÆ® ºÎ»ê±¤¿ª½Ã ºÎ»êÁø±¸ °¡¾ßµ¿ ¤Ó °³ÀÎÁ¤º¸Ãë±Þ¹æħ
Copyright ¨Ï musictrot All rights reserved.