Android 09 服务的简单使用
Posted 今晚看星星
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 09 服务的简单使用相关的知识,希望对你有一定的参考价值。
1 服务介绍
- 服务(Service) android中的四大控件,它能够长期在后台运行并不提供用户界面
- 即使用户切换到另一个应用程序,服务仍能够在后台运行
2 服务创建
- 创建Service子类
public class MyService extends Service {
public IBinder onBind(Intent arg0) {
return null;
}
}
- 在清单文件
manifest.xml
中配置服务
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
3 服务的启动方式与生命周期
3.1 服务的启动方式
- 通过
startService(Intent intent)
启动
// 开启服务
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
- 通过其他组件调用
stopService(intent)
方法将服务停止,或者自身调用stopService(Intent intent)
// 关闭服务
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
3.2 生命周期
服务生命周期方法
onCreate()
:第一次创建服务时执行的方法onDestroy()
:服务被Android销毁是执行的方法onStartCommand()
:访问者通过startService(Intent intent)
启动服务时执行的方法onBInd()
: 使用bindService(Intent intent, ServiceConnection serviceConnection, Context.MODE)
调用的方法onUnBind()
:使用unbindService(ServiceConnection serviceConnection)
时调用
4 创建服务
4.1 新建服务
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
public MyService() {
}
@Override
public void onDestroy() {
Log.i("service_life", "onDestory");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("service_life", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
Log.i("service_life", "onCreate");
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
4.2 在UI线程中调用服务
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 开启服务
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 关闭服务
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
//
private Button button1, button2;
}
以上是关于Android 09 服务的简单使用的主要内容,如果未能解决你的问题,请参考以下文章
片段中的TextView在Android Studio中返回Null