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());