Android简单音乐播放器
Service作为Android四大组件之一,通常被称为“后台服务”具体是指其本身的运行并不依赖于用户可视的UI界面,实际应用,Service的适用场景应该具备以下条件:
(1)并不依赖于用户可视的UI界面(当然,这一条其实也不是绝对的,如前台Service就是与Notification界面结合使用的);
(2)具有较长时间的运行特性。
1. ServiceAndroidManifest.xml 声明(android:name对应Service类名,android:permission是权限声明,android:process设置具体的进程名称)
2. service android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:isolatedProcess=["true" | "false"] android:label="string resource" android:name="string" android:permission="string" android:process="string" > . . . </service>
3. StartedService
(onBind(...)函数是Service基类中的唯一抽象方法,子类都必须重写实现,此函数的返回值是针对BoundService类型的Service才有用的,在StartedService类型中,此函数直接返回 null 即可)
Started Service自定义:
public class MyService extends Service { public static final String TAG = "MyService"; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.w(TAG, "in onCreate"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.w(TAG, "in onStartCommand"); Log.w(TAG, "MyService:" + this); String name = intent.getStringExtra("name"); Log.w(TAG, "name:" + name); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
Started Service使用:
public class MainActivity extends Activity { public static final String TAG = "MainActivity"; private Button startServiceBtn; private Button stopServideBtn; private Button goBtn; private Intent serviceIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startServiceBtn = (Button) findViewById(R.id.start_service); stopServideBtn = (Button) findViewById(R.id.stop_service); goBtn = (Button) findViewById(R.id.go); startServiceBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { serviceIntent = new Intent(MainActivity.this, MyService.class); startService(serviceIntent); } }); stopServideBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(serviceIntent); } }); goBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, BActivity.class); startActivity(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); Log.w(TAG, "in onDestroy"); } }
Started Service生命周期及进程相关(onCreate(Client首次startService(..)) >> onStartCommand >> onStartCommand -optional ... >> onDestroy(Client调用stopService(..))):
<service android:name=".MyService" android:exported="true" android:process=":MyCorn" > <intent-filter> <action android:name="com.example.androidtest.myservice" /> </intent-filter> </service>
Started Service Client与Service通信相关:
当Client调用startService(Intent serviceIntent)启动Service时,Client可以将参数通过Intent直接传递给Service。Service执行过程中,如果需要将参数传递给Client,一般可以通过借助于发送广播的方式(此时,Client需要注册此广播)。