from:
http://blog.csdn.net/pugongying1988/article/details/7239124
1. register a service in manifest file . A stupid mistake that takes me one hour is that , the Four Big Parts(Activity, ContentProvider , Service , BroadcastReceiver ) must be registered INSIDE the APPLICATION !
Only the permissions must be writen outside the application label , better to be written before the application label .
2. set an intent filter for the service .
<service android:enabled="true" android:name="MusicService"> <intent-filter> <action android:name="com.service_test.MusicService"/> </intent-filter> </service>
3. create a CustomService extends Service. Override the onCreate(), onDestroy() , on StartCommand() .
4. use .startService(Intent intent) to start the Service . It will run in the system background or use the
.stopService(Intent intent) to stop it;
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.service_test" android:versionCode="1" android:versionName="1.0"> <application android:label="@string/app_name" > <activity android:name="ServiceTest" 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:enabled="true" android:name="MusicService"> <intent-filter> <action android:name="com.service_test.MusicService"/> </intent-filter> </service> </application> </manifest>
package com.service_test; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; public class ServiceTest extends Activity { private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private Button closeBtn; public static final int ID_PLAY=1; public static final int ID_STOP=2; public static final int ID_PAUSE=3; public static final int ID_EXIT=4; public static final int ID_CLOSE=5; private LinearLayout ll; private LinearLayout.LayoutParams params; private OnClickListener clickListener=new OnClickListener(){ public void onClick(View v) { // throw new UnsupportedOperationException("Not supported yet."); int op=-1; Intent intent=new Intent(); intent.setAction("com.service_test.MusicService"); switch(v.getId()){ case ServiceTest.ID_PLAY: Log.i("l","play music"); op=ServiceTest.ID_PLAY; break; case ServiceTest.ID_STOP: Log.i("l","stop music"); op=ServiceTest.ID_STOP; break; case ServiceTest.ID_PAUSE: Log.i("l","pause music"); op=ServiceTest.ID_PAUSE; break; case ServiceTest.ID_EXIT: Log.i("l","exit"); // op=ServiceTest.ID_EXIT; ServiceTest.this.finish(); stopService(intent); break; case ServiceTest.ID_CLOSE: Log.i("l","close"); // op=ServiceTest.ID_CLOSE; ServiceTest.this.finish(); break; }//end switch Bundle bundle=new Bundle(); bundle.putInt("op",op); intent.putExtras(bundle); ServiceTest.this.startService(intent); Log.i("l","sendout op:"+op); // sendBroadcast(intent); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); params=new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); ll=new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); playBtn=new Button(this); playBtn.setId(ServiceTest.ID_PLAY); playBtn.setText("play"); ll.addView(playBtn, params); stopBtn=new Button(this); stopBtn.setId(ServiceTest.ID_STOP); stopBtn.setText("stop"); ll.addView(stopBtn,params); pauseBtn=new Button(this); pauseBtn.setId(ServiceTest.ID_PAUSE); pauseBtn.setText("pause"); ll.addView(pauseBtn,params); exitBtn=new Button(this); exitBtn.setId(ServiceTest.ID_EXIT); exitBtn.setText("exit"); ll.addView(exitBtn,params); closeBtn=new Button(this); closeBtn.setId(ServiceTest.ID_CLOSE); closeBtn.setText("close"); ll.addView(closeBtn); setContentView(ll); playBtn.setOnClickListener(clickListener); stopBtn.setOnClickListener(clickListener); pauseBtn.setOnClickListener(clickListener); exitBtn.setOnClickListener(clickListener); closeBtn.setOnClickListener(clickListener); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.service_test; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.IBinder; import android.util.Log; /** * * @author Administrator */ public class MusicService extends Service{ private static final String TAG="MusicService"; private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent arg0) { // throw new UnsupportedOperationException("Not supported yet."); return null; } @Override public void onCreate() { super.onCreate(); Log.i("l","onCreate"); if(mediaPlayer==null){ mediaPlayer=MediaPlayer.create(this, R.raw.nine_crimes); mediaPlayer.setLooping(false); } } @Override public void onDestroy() { Log.i("l","onDestroy"); if(mediaPlayer!=null){ mediaPlayer.stop(); mediaPlayer.release(); } super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("l","onStartCommand"); if(intent!=null){ Bundle bundle=intent.getExtras(); if(bundle!=null){ int op=bundle.getInt("op"); switch(op){ case ServiceTest.ID_PLAY: play(); break; case ServiceTest.ID_STOP: stop(); break; case ServiceTest.ID_PAUSE: pause(); break; default: break; } } } return super.onStartCommand(intent, flags, startId); } private void play(){ if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); } } private void stop(){ if(mediaPlayer!=null){ mediaPlayer.stop(); try{ //after use .stop() function , must use .prepare() function before .start() again; mediaPlayer.prepare(); } catch(Exception ex){ Log.e("l","music stop exception:"+ex); } } } private void pause(){ if(mediaPlayer!=null && mediaPlayer.isPlaying()){ mediaPlayer.pause(); } } }
from the website :
http://blog.csdn.net/pugongying1988/article/details/7239124
there is another method , which is to bind the service to the activity :
public class PlayBindMusic extendsActivityimplementsOnClickListener { privatestaticfinal String TAG = "PlayBindMusic"; privateButton playBtn; privateButton stopBtn; privateButton pauseBtn; privateButton exitBtn; privateBindMusicService musicService; @Override publicvoidonClick(View v) { switch(v.getId()) { caseR.id.play: Log.d(TAG,"onClick: binding srvice"); musicService.play(); break; caseR.id.stop: Log.d(TAG,"onClick: stoping srvice"); if(musicService !=null){ musicService.stop(); } break; caseR.id.pause: Log.d(TAG,"onClick: pausing srvice"); if(musicService !=null){ musicService.pause(); } break; caseR.id.exit: Log.d(TAG,"onClick: exit"); this.finish(); break; } } privatevoidconnection(){ Log.d(TAG,"connecting....."); Intent intent =newIntent("org.allin.android.bindService"); bindService(intent, sc, Context.BIND_AUTO_CREATE); } privateServiceConnection sc =newServiceConnection() { @Override publicvoidonServiceDisconnected(ComponentName name) { musicService =null; Log.d(TAG,"in onServiceDisconnected"); } @Override publicvoidonServiceConnected(ComponentName name, IBinder service) { musicService = ((BindMusicService.MyBinder)(service)).getService(); if(musicService !=null){ musicService.play(); } Log.d(TAG,"in onServiceConnected"); } }; }
/** * @author allin.dev *http://allin.cnblogs.com/ */ public class BindMusicService extendsService { privatestaticfinal String TAG = "MyService"; privateMediaPlayer mediaPlayer; privatefinalIBinder binder =newMyBinder(); publicclassMyBinder extendsBinder { BindMusicService getService() { returnBindMusicService.this; } } /* * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override publicIBinder onBind(Intent intent) { Log.d(TAG,"onBind"); play(); returnbinder; } @Override publicvoidonCreate() { super.onCreate(); Log.d(TAG,"onCreate"); Toast.makeText(this,"show media player", Toast.LENGTH_SHORT).show(); } @Override publicvoidonDestroy() { super.onDestroy(); Log.d(TAG,"onDestroy"); Toast.makeText(this,"stop media player", Toast.LENGTH_SHORT); if(mediaPlayer !=null){ mediaPlayer.stop(); mediaPlayer.release(); } } publicvoidplay() { if(mediaPlayer ==null) { mediaPlayer = MediaPlayer.create(this, R.raw.tmp); mediaPlayer.setLooping(false); } if(!mediaPlayer.isPlaying()) { mediaPlayer.start(); } } publicvoidpause() { if(mediaPlayer !=null&& mediaPlayer.isPlaying()) { mediaPlayer.pause(); } } publicvoidstop() { if(mediaPlayer !=null) { mediaPlayer.stop(); try{ // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数 mediaPlayer.prepare(); }catch(IOException ex) { ex.printStackTrace(); } } } }