1. 程式人生 > >Android使用本地Service實現後臺播放音樂

Android使用本地Service實現後臺播放音樂

配置檔案

 <service android:name=".MyService"></service>

佈局

  <Button
        android:id="@+id/btn_open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

原始碼

activity:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button btn_open;
    private boolean status=false;
    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intent=new Intent(this,MyService.class);
        btn_open= (Button) findViewById(R.id.btn_open);
        btn_open.setText("open ");
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!status){
                    btn_open.setText("close");
                    startService(intent);//呼叫onCreate的方法
                    status=true;
                }else{
                    btn_open.setText("open");
                    stopService(intent);//呼叫onDestory方法
                    status=false;
                }
            }
        });
    }
}

Service:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyService extends Service {
    MediaPlayer mediaPlayer;

    //必須要實現此方法,IBinder物件用於交換資料,此處暫時不實現
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer =MediaPlayer.create(this,R.raw.citylights);
        Log.e("TAG","create");

    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        play();
        Log.e("TAG","start");
        return super.onStartCommand(intent, flags, startId);
    }

    //封裝播放
    private void play() {
        mediaPlayer.start();
    }

    //service被關閉之前呼叫
    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        Log.e("TAG","destoryed");
    }
}

總結:

本文主要是探究Service的工作原理 (1)Service的子類必須onBind方法,用於與使用者交換資料,返回型別是IBinder型別,如果要實現遠端Service,則需要建立一個繼承Binder類的子類,然後在使用者活動視窗中實現ServiceConnection類中的兩個方法:onServiceConnection()方法和onServiceDisConnected()方法。 (2)本地服務一旦被建立就會一直存在,即使呼叫它的startService()的元件被銷燬也存在後臺中,除非呼叫stopService()銷燬它,或者在Servicec內部呼叫stopSelf()自毀。
(3)在外部啟動Service的方法分別與Service子類方法對應的是 startService()——onCreate();stopService——onDestoryed(). (4)值得注意的是Service一旦建立直到被銷燬,其onCreate()方法只會被呼叫一次。其從建立到被銷燬的生命週期是: onCreate()-onStartCommand()-服務執行中-服務被停止-onDetory().