Android使用本地Service实现后台播放音乐

来源:互联网 发布:解除windows驱动器锁定 编辑:程序博客网 时间:2024/06/05 06:32

配置文件

 <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().





0 0