當需要建立在後台啟動並執行程式的時候,就要使用到Service。Service 可以分為有無限生命和有限生命兩種。特別需要注意的是Service跟Activities是不同的(簡單來說可以理解為後台與前台的區別),例如,如果
需要使用Service的話,需要調用startService(),從而利用startService()去調用Service中的 OnCreate()和onStart()方法來啟動一個背景Service。
啟動一個Service的過程如
下:context.startService() ->onCreate()- >onStart()->Service running其中onCreate()可以進行一些服務的初始化工作,onStart()則啟動服務。
停止一個Service的過程如下:context.stopService() | ->onDestroy() ->Service stop
接下來的執行個體是一個利用後台服務播放音樂的小例子,點擊start運行服務,點擊stop停止服務。
MainActivity的原始碼:
package com.example.test1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button playButton = null;
private Button stopButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playButton = (Button)findViewById(R.id.startPlayButton);
stopButton = (Button)findViewById(R.id.stopPlayButton);
playButton.setOnClickListener(new ButtonListen());
stopButton.setOnClickListener(new ButtonListen());
}
class ButtonListen implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.startPlayButton:
startService(new Intent(MainActivity.this, MyService.class));
break;
case R.id.stopPlayButton:
stopService(new Intent(MainActivity.this, MyService.class));
break;
default:
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyService的原始碼:
package com.example.test1;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
MediaPlayer player = null;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this,
"MyService Createed!",
Toast.LENGTH_SHORT).show();
player = MediaPlayer.create(this, R.raw.burning);
player.setLooping(false);
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this,
"MyService onStart!",
Toast.LENGTH_SHORT).show();
player.start();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
player.stop();
Toast.makeText(this,
"MyService onDestroy",
Toast.LENGTH_SHORT).show();
}
}
源碼稍後提供下載:http://download.csdn.net/detail/yanzi1225627/4463948