实验九Service
一、实验目的及任务
1、Service的创建和使用
2、Service的配置
二、实验环境
1、Jdk
2、Android Studio
三、实验步骤
编写一个Service类,里面有求一个1~n之和的方法。
编写一个Activity类,里面有绑定、解除绑定、输入一个上届数字n的输入框、计算和的按钮、显示结果的输入框。
当单击绑定按钮时,绑定启动Service;
当单击解除绑定按钮时解除与Service的绑定;
输入完上届数字后,当单击求和按钮时,调用Service的求和方法,并将结果显示到显示结果的输入框中;
实现效果
代码
项目目录
CalculatorService.java
public class CalculatorService extends Service {
class MyBinder extends Binder{
CalculatorService getService(){
return CalculatorService.this;
}
}
MyBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent){
return binder;
}
public CalculatorService(){
super();
}
public void onCreate(){
super.onCreate();
}
public boolean onUnbind(Intent intent){
return true;
}
public void onDestroy() {
super.onDestroy();
}
//业务逻辑
public int getSum(int n){
int sum=0;
for(int i=1;i<=n;i++){
sum += i;
}
return sum;
}
}
Service需要在manifest中注册
<service android:name=".CalculatorService">
<intent-filter>
<action android:name="service"></action>
</intent-filter>
</service>
调用Service的MainActivity类
public class MainActivity extends AppCompatActivity {
EditText maxNum, dasRes;
CalculatorService.MyBinder binder;//CalculatorService中的MyBinder内部类
CalculatorService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maxNum = findViewById(R.id.maxNum);
dasRes = findViewById(R.id.dasRes);
}
//属性, 相当于javaweb JDBC中的connection连接对象
public ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder = (CalculatorService.MyBinder)iBinder;
service = binder.getService();
System.out.println("Connect");
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("Disconnect");
}
};
//onclick: 用于启动后台Service服务
public void StartService(View view){
Intent intent = new Intent(this, CalculatorService.class);
intent.setAction("1");
bindService(intent, connection, Service.BIND_AUTO_CREATE);
Toast.makeText(this,"绑定成功",Toast.LENGTH_LONG).show();
}
//onclick: 用于停止后天的Service服务
public void StopService(View view){
unbindService(connection);
Toast.makeText(this,"解除绑定",Toast.LENGTH_LONG).show();
}
//onclick: 用于显示计算结果数字的(其实计算也就是在这一步发生的)
public void ShowResult(View view){
if (maxNum.getText().toString().length() == 0) return;
int result = service.getSum(Integer.parseInt(maxNum.getText().toString()));
dasRes.setText(String.valueOf(result));
Toast.makeText(this,"计算成功",Toast.LENGTH_LONG).show();
}
}