service是android的一个组件,相当于一个没有界面的activity,每个service都要在mainfest中进行注册,service有两种启动方式:Context.startService()和Context.bindService().
public class MyService extends Service{ String TAG = "MyService"; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } }
<service android:name="com.example.servicetest.MyService"> </service>
public class MainActivity extends Activity { Intent serviceIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceIntent = new Intent(this , MyService.class); Button startButton = (Button)findViewById(R.id.startbutton); startButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub //启动service startService(serviceIntent); } }); Button stopButton = (Button)findViewById(R.id.stopbutton); stopButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub //停止service stopService(serviceIntent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/startbutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="startService"/> <Button android:id="@+id/stopbutton" android:layout_below="@id/startbutton" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="stopService"/> </RelativeLayout>
这其实就是对service的一个完美诠释:
在activity里调用startService()之后在service里onCreate()->onStartCommand()
而在activity里调用stopService()之后在service里onDestroy(),即service终止
后记:用这种方法启动的service和actiivty没联系,但是在默认情况下是在同一进程的同一线程中的,如果此时终止activity,service还会继续运行,但是由于service在系统中的优先级较低,在内存不足时可能会被系统收回。