Android使用本地Service實現後臺播放音樂
阿新 • • 發佈:2019-01-04
配置檔案
<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"); } }