直接上码简单易懂
package com.example.day601; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; /** * 后台播放···网络音频 采用service来实现 * 本地Service 远程Service * 此处如果将Service实现为内部类将会出现"has no paramer constructor" * */ public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button start,stop;//开启关闭service private Intent serviceIntent;//启动service所需Intent @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start=(Button)findViewById(R.id.start); stop=(Button)findViewById(R.id.stop); serviceIntent=new Intent(this,SimpleServiceIntent.class); start.setOnClickListener(this); stop.setOnClickListener(this); } @Override public void onClick(View v) { if (v == start) { startService(serviceIntent); //点击start后一次调用onCreate() onStartCommand() } else if (v == stop) { stopService(serviceIntent); } } }
package com.example.day601; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; public class SimpleServiceIntent extends Service { public SimpleServiceIntent() { } /** * @param intent * @return null * 没有需要绑定的任务,该方法返回null */ @Nullable @Override public IBinder onBind(Intent intent) { return null; } /** * 实例化Service时调用 */ @Override public void onCreate() { super.onCreate(); Log.i("Service", "onCreate"); } /** * @param intent * @param flags * @param startId * @return START_STICKY表明如果结束了该服务,那么将重新启动该服务 * android 2.0后引入了该方法 每当调用startService时就会调用该方法 */ @Override public int onStartCommand(Intent intent, int flags, int startId) { // return super.onStartCommand(intent, flags, startId); Log.i("Service", "onStartCommand"); return START_STICKY; } /** * @param intent * @param startId 2.0之前的版本调用该onStart方法 */ @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.i("Service", "onStart"); } @Override public void onDestroy() { super.onDestroy(); Log.i("Service", "onDestroy"); } }