public IBinder onBind(Intent intent) {
return null;
}
}
- 2.创建ServiceActivity.java和配套的activity_service.xml文件,其代码如下:
public class ServiceActivity extends ActivityBase {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
Intent intentStart = new Intent(ServiceActivity.this, StartService.class);
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intentStart);
}
});
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intentStart);
}
});
}
}
- 配套的activity_service.xml文件
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:id=“@+id/ll_bg”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
android:background=“@color/color_666666”>
<Button
android:id=“@+id/btn_start”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“start启动服务”/>
<Button
android:id=“@+id/btn_stop”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“start停止服务”/>
- 3.添加Service组件声明,在AndroidManifest.xml文件中声明一个Service组件,其代码如下:
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“com.scc.demo”>
<application
…>
<activity
…>
…
- 运行结果
07-07 16:41:11.474 E/-SCC-: com.scc.demo.actvitiy.ServiceActivityonCreate
07-07 16:41:11.481 E/-SCC-: com.scc.demo.actvitiy.ServiceActivityonStart
07-07 16:41:11.482 E/-SCC-: com.scc.demo.actvitiy.ServiceActivityonResume
07-07 16:41:13.313 E/-SCC-com.scc.demo.service.StartService: onCreate
07-07 16:41:13.334 E/-SCC-com.scc.demo.service.StartService: onStartCommand
07-07 16:41:16.705 E/-SCC-com.scc.demo.service.StartService: onDestroy