服务Service

服务和Activity不交互
public class MyService extends Service {
public static final String TAG="MyService";
private MediaPlayer mediaPlayer;

@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG, "onBind: "+System.currentTimeMillis());
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mediaPlayer.start();
    Log.i(TAG, "onStart: "+System.currentTimeMillis());
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    mediaPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/sdcard/remix.mp3")) );
    mediaPlayer.setLooping(false);
    Log.i(TAG, "onCreate: "+System.currentTimeMillis());
    Log.i(TAG, "onCreate: "+Thread.currentThread().toString());
    Log.i(TAG, "onCreate: "+Thread.currentThread().getId());
    Log.e(TAG, "onCreate: "+ Process.myPid());
}

@Override
public void onDestroy() {
    mediaPlayer.stop();
    Log.i(TAG, "onDestroy: "+ System.currentTimeMillis());
  }
}

 @Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.start:
            startService(new Intent("com.iflytek.MYSERVICE"));
            //startService(new Intent(this,MyService.class));
            Log.i(TAG, "onClick: start Service");
            break;
        case R.id.stop:
            stopService(new Intent("com.iflytek.MYSERVICE"));
            Log.i(TAG, "onClick: stop Service");
            break;
        default:
            break;
    }
}
服务和Activity交互

你可能感兴趣的:(服务Service)