如何在android中建立一个服务?
使用androidstudio新建一个继承自Service的MyService类,并在Android manifest.xml文件中注册,
在MyService类中需要实现onBind这个类,但是启动一个服务不一定会用得到它,使用aidl启动服务时才会调用这个方法,现在可以先让这个方法的返回值为null:
@Override
public IBinder onBind(Intent intent) {
return null;
}
为了更能直观的感受到服务的创建,我们需要了解一下服务的生命周期,在MyService类中覆写onCreate,onStartCommand,onDestroy()者几个方法,并在方法中对控制台输出信息,把布局文件的布局方式改成线性布局,添加两个按钮,分别用来启动和停止服务:
MyService中覆写的方法:
@Override
public void onCreate() {
Log.d(TAG, "onCreate: ");
super.onCreate();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
activity对应的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:text="start"
android:onClick="start"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="end"
android:onClick="end"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
启动一个服务的方式和启动一个activity的方式很像,新建一个Intent对象,指定对应的Service的class,再使用activity中提供的 startService()就可以直接启动服务,类似,使用stopService()就会停止目标服务:
activity中的代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View view) {
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void end(View view) {
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
依次点击按钮start(第一次启动服务) ----> start(再次启动服务) ------> end(销毁服务) ------>start(重新启动服务),可以看到Androidstudio中控制提输出以下信息:
我们可以看到,当服务启动时,首先会调用onCreate方法,然后再调用onStartCommand方法,如果再按一次start按钮,就只会调用onStartCommand方法,onCreate方法只会调用一次,停止服务时会调用onDestroy方法,此时服务已经销毁了,再次启动服务时就会重新调用onCreate方法