package com.iteedu.playservice;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class PlayService extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.start);
button1.setOnClickListener(startIt);
Button button2 = (Button)findViewById(R.id.stop);
button2.setOnClickListener(stopIt);
}
private OnClickListener startIt = new OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(
"com.iteedu.playservice.START_AUDIO_SERVICE"));
}
};
private OnClickListener stopIt = new OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(
"com.iteedu.playservice.START_AUDIO_SERVICE"));
finish();
}
};
}
package com.iteedu.playservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class Music extends Service {
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
player = MediaPlayer.create(this, R.raw.gequ);
player.start();
}
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
<activity android:name=".PlayService"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Music">
<intent-filter>
<action android:name="com.iteedu.playservice.START_AUDIO_SERVICE" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>