您的位置:首页 > 移动开发 > Android开发

Android课堂学习笔记————Service

2018-03-22 00:21 417 查看

什么是Service

1.Service是Android四大组件之一,和Activity的级别相当

2.Service第可以长时间运行在后台的,是不可见是没有界面的组件

3.Service是运行在主线程中的

4.Service可以跨进程调用

如何使用Service

1.新建类继承Service

2.重写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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: