Android课堂学习笔记————Service
2018-03-22 00:21
417 查看
什么是Service
1.Service是Android四大组件之一,和Activity的级别相当2.Service第可以长时间运行在后台的,是不可见是没有界面的组件
3.Service是运行在主线程中的
4.Service可以跨进程调用
如何使用Service
1.新建类继承Service2.重写onCreate方法
3.实现onBind方法
4.重写onStartCommand方法
5.重写onDestroy方法
6.在AndroidManifest中注册Service
7.在有Context环境中通过startService启动Service
8..在有Context环境中通过stopService停止Service
代码展示
java代码public class MainActivity extends AppCompatActivity implements View.OnClickListener{ //定义两个按钮来向Service发信息 private Button startBtn; private Button stopBtn; public String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //绑定id与监听事件 startBtn = findViewById(R.id.start_service); stopBtn = findViewById(R.id.stop_service); startBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.start_service: //和Activity一样都用Intent传值 Intent startIntent = new Intent(this, MyService.class); //启动service用startService方法 startService(startIntent); break; case R.id.stop_service: Intent stopIntent = new Intent(this, MyService.class); //停止service用stopService方法 stopService(stopIntent); break; default: break; } } }
继承Service类
public class MyService extends Service { public String TAG = "MyService"; @Override public void onCreate() { super.onCreate(); //定义log方法在后台打印 Log.e(TAG, "onCreate() ++++++++++++++++++++++++++++++++++++++++++"+Thread.currentThread().getName()); } @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "onDestroy() ++++++++++++++++++++++++++++++++++++++++++++"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand() ++++++++++++++++++++++++++++++++++++++++"); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
相关文章推荐
- Android Service学习笔记
- android bind service 学习笔记
- Android 学习 笔记_11. Service初步
- Android Service学习笔记
- android service的学习笔记
- Android 学习笔记 Service (一) Local Service
- Android Service学习笔记
- Android开发学习笔记:Service的简介和启动方式
- Android开发学习笔记:Service的远程调用
- Android 学习笔记 Service 启动
- Android开发学习笔记:Service的远程调用
- Android应用开发学习笔记之Service
- Android开发学习笔记:Service的远程调用
- Android开发学习笔记(2):Service的简介和启动方式
- Android开发学习笔记:Service的远程调用
- android bind service 学习笔记
- android service 服务学习笔记
- Android开发学习笔记:Service的简介和启动方式
- Android Service学习笔记
- Android菜鸟笔记-由startService到bindService的学习