회원가입아이디/비번찾기
실시간 TV
홈으로
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, " onDestroy()");
        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, " onReceive : ACTION_MEDIA_EJECT");
                        System.setProperty(PROR_STARTPAY, "false");
                        if (!songList.isEmpty()) {
                            songList.clear();
                        }
                        if (mPlayer == null) {
                            return;
                        } else {
                            //Log.d(MYTAG, " onReceive : is mPlayer null?? ");
                                Log.d(MYTAG, " onReceive : 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, " onReceive : 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;
        }
    }
}
추천추천 : 511 추천 목록
번호 제목
1,346
 윈도우 서버 2019 취약점 점검 보안
1,345
 윈도우 서버 2019 취약점 점검 보안 (windows server 2019)
1,344
 Windows 취약점진단 보안가이드라인
1,343
 Windows Admin Center를 통한 서버 관리
1,342
 윈도우 서버에서 실행되는 서비스 확인
1,341
 Chrome NET::ERR CERT REVOKED 해결방법
1,340
 cmd 명령어 (명령 프롬프트 명령어) 모음
1,339
 Windows10 특정 프로그램(OCS 2007 R2)에서 첨부파일 드래그앤드롭이 안 되는 현상
1,338
 윈도우 로그, 관리 이벤트 삭제
1,337
 클린 부팅
1,336
 Windows 구성 요소 저장소에서 파일 손상 검사
1,335
 Windows Defender 검사 기록 삭제하기
1,334
 간단한 윈도우 10 정품 인증 (크랙프로그램 필요없음)
1,333
 오류난 폴더 강제삭제 방법
1,332
 크롬에서 플래시 항상 허용하도록 설정하기 (레지스트리) reg 파일 만들기
1,331
 GPT 디스크를 MBR 디스크로 변환
1,330
 MBR 디스크를 GPT 디스크로 변환
1,329
 구글 검색을 200% 활용하게 해주는 검색 명령어 총정리
1,328
 [Jquery] jQuery로 우클릭 방지, 드래그 방지, 선택 방지 (IE10, 파이어폭스, 크롬 확인)
1,327
 php 사용자 접속IP, 브라우저정보, os정보, http, https 접속프로토콜 알아오기
1,326
 [PHP] IE 브라우저 접속 검출하기
1,325
 윈도우10 시스템 예약 파티션 확인 및 삭제
1,324
 윈도우10 복구 파티션 삭제 방법
1,323
 윈도우10 부팅지연 검은화면에서 몇분간 머무는 현상 해결방법
1,322
 삼성노트북 바이오스 진입이 불가능한 경우 바이오스 재설치와 NVRAM 초기화
1,321
 익스플로러(IE)의 구글 검색공급자 한글로 변경 방법
1,320
 윈도우 10 기본 앱 삭제 및 복구
1,319
 meta 태그 http-equiv 설정방법과 차이점
1,318
 구글(Google)검색에서 고급연산자를 이용하여 많은 정보를 얻는 방법
1,317
 프로그램 없이 하드디스크 복사 및 백업하기
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침
Copyright ⓒ musictrot All rights reserved.