ServiceDemo.java:
public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.w(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
startActivity(new Intent(getApplicationContext(),Second.class));
break;
case R.id.buttonStop:
Log.w(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
MyService.java:
package com.example;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
Log.w(" ibinder ","");
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created",0).show();
Log.w(TAG, "onCreate");
player = MediaPlayer.create(this,R.raw.frm7v1);
player.setLooping(true); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped",0).show();
Log.w(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started :"+intent+" start id :"+startid,0).show();
Log.d(TAG, "onStart");
player.start();
}
}
Объявите следующий атрибут в файле манифеста:
<service android:enabled="true" android:name=".MyService" />