package com.lxz.app11;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
//输出计算结果案例
public class CalculateActivity extends AppCompatActivity {
//是不是注册标志
private boolean flag=false;
//Service
Calculate service=null;
//连接对象
ConnectionUtil conn=null;
//Mybinder对象,用于获取Service
Calculate.MyBinder binder=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
}
//解绑服务
public void unBindService11(View view) {
if (flag){
unbindService(conn);
flag=!flag;
}
else
{
Toast.makeText(getApplicationContext(), "暂为可解绑的服务!", Toast.LENGTH_SHORT).show();
}
}
//阶乘
public void textgetJiecheng(View view) {
if (flag){
TextView textView=findViewById(R.id.textnumber);
TextView result=findViewById(R.id.result);
if (textView.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(), "请输入有效数字!", Toast.LENGTH_SHORT).show();
}
else{
result.setText(service.getJieCheng( Long.parseLong(textView.getText().toString().trim()))+"");
}
}
else
{
Toast.makeText(getApplicationContext(), "请先绑定服务!", Toast.LENGTH_SHORT).show();
}
}
//求和
public void textgetSum(View view) {
if (flag){
TextView textView=findViewById(R.id.textnumber);
TextView result=findViewById(R.id.result);
if (textView.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(), "请输入有效数字!", Toast.LENGTH_SHORT).show();
}
else{
result.setText(service.getSum( Integer.parseInt(textView.getText().toString().trim()))+"");
}
}
else
{
Toast.makeText(getApplicationContext(), "请先绑定服务!", Toast.LENGTH_SHORT).show();
}
}
//服务绑定
public void bindService11(View view) {
if (!flag){
conn=new ConnectionUtil();
Intent intent=new Intent();
intent.setClass(getApplicationContext(),Calculate.class);
intent.putExtra("code","200");
bindService(intent,conn,BIND_AUTO_CREATE);
flag=!flag;
}
else
{
Toast.makeText(getApplicationContext(), "请不要重复绑定!", Toast.LENGTH_SHORT).show();
}
}
//连接类
private class ConnectionUtil implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//获取binder对象
binder= (Calculate.MyBinder) iBinder;
//获取service
service=binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
binder=null;
service=null;
}
}
}