홈으로 홈으로 | 무료회원가입 | 아이디/비번찾기 | 즐겨찾기
추천음악방송메인홈1대1상담음악방송청취
뽕짝아가씨(무료음악채널)
okTrot(무료음악채널)
전통가요(무료음악채널)
음악가사 검색
온라이브스토어(앱다운로드)
온라이브(방송등록및청취)
비디오 베스트 50
금영노래방
TJ노래방
유튜브 동영상 다운로드
POP Player
신나는 고스톱
컴퓨터 오목
작은 음악다방
운.영.자.1대1.상담
FAQ\지원.프로그램
Q&A\고.객.지.원

자동러시 웹플레이어신청

보안∵서버∵쿠키
윈도우∵프레임
이미지∵배경
시간∵달력∵계산
상태바∵타이틀바
음악∵영상
폼∵전송∵테이블
키보드∵마우스
효과∵링크∵메뉴
Script∵php
기타
PHP 강좌
윈도우관련팁
웹관련팁
홈페이지제작팁
기본강좌
레지스트리
윈도우서버
리눅스서버
Android
Service 등록하기
2년 전
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;
        }
    }
}
추천추천 : 101 추천 목록
번호 제목
1,315
 포토샵 psd 파일 연결 레지스트리(registry) 편집
1,314
 윈도 10 최신 업데이트 후 인터넷 속도의 저하가 발생할 때 조치 사항
1,313
 Autotuning level 해제 (윈도우비스타 이상 윈도우)인터넷 속도 빠르게 하는 방법
1,312
 윈도우에서 특정프로세스를 일괄 종료하는법
1,311
 MediaPlayer 클래스 사용법
1,310
 안드로이드에서 audio player 실행하기
1,309
 [Android] MediaPlayer 음악재생기 만들기
1,308
 Eclipse와 Android NDK 연동하기
1,307
 Android Sliding Drawer Functionality 안드로이드 슬라이딩 드로우 예제 sample
1,306
 Android Speech To Text
1,305
 Android WebPageLoader with progress-bar
1,304
 Android Text To Speech(TTS)
1,303
 Android Playing Audio from a web url
1,302
 Button height different from background height in Android image design
1,301
 Android Getting Started with Material Design
1,300
 Using toast inside timertask perfect
1,299
 네트워크 상태 [Android]
1,298
 Webview source [Android]
1,297
 공유 Intent [Android]
1,296
 intent uri 모음 [Android]
1,295
 http requestWebViewClient [Android]
1,294
 캐시 삭제
1,293
 캐시 지우기 [Android]
1,292
 바로풀어(수학 문제 질의응답 SNS) 에 사용된 오픈소스 라이브러리 [Android]
1,291
 Webviw [Android]
1,290
 오픈소스 라이브러리 모음 [Android]
1,289
 Android webview 개발시 알아둬야 할 것들 [Android]
1,288
 webview 동영상 재생 [Android]
1,287
 [Android] Webview 404 에러 처리
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 메소드
목록
인기절정뽕짝파티
트로트재생목록
인기트로트모음
지루박디스코메들리
밤무대애창곡
전자올겐경음악
종합성인가요방
못잊을옛날노래
카바레 음악
트롯디스코팡팡
관광 메들리
트롯카페
가요감상실
추억의옛노래
스페셜가요광장
BillBoard Free
추천가요모음
경음악.전자올겐
스페셜음악여행
WOLRD POPs
K-POP\BillBoard
JP\CN
POP TOP BEST
K.R.노래방

추천가요\인기
F뮤직 인기\발라드
F뮤직 애창\트로트
트로트성인가요
인기가요
프리미엄 POP
경음악\기타
프리미엄 최신가요
프리미엄 성인가요
가요1번지(종합)
뮤직하우스
동요\연변\반주\기타
가요축제\트롯1번지
댄스\메들리\리믹스
카페\명상\경음악\기타
뮤직트로트 부산광역시부산진구 가야동 ㅣ 개인정보취급방침
Copyright (C) musictrot All rights reserved.