一、服务是什么
Service是安卓中实现程序后台运行的解决方案,适合去执行不需要和用户交互且还要长期运行的项目。如下载、音乐播放等。服务的运行不依赖于任何用户界面。
二、服务的基本用法
1、启动和停止服务
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始服务"/>
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止服务"/>
</LinearLayout>
New——>Service——>Service创建一个服务
MyService.java
public class MyService extends Service {
public MyService() {
}
//服务创建时调用
@Override
public void onCreate() {
super.onCreate();
Log.d("MyService","onCreate executed");
}
//服务启动时调用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService","onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
//服务销毁时调用
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService","onDestory executed");
}
//服务被绑定时调用
@Override
public IBinder onBind(Intent intent) {
Log.d("MyService","onBind executed");
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button startService;
private Button stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = findViewById(R.id.start_service);
stopService = findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.start_service: