import android.content.ComponentName; import android.content.Intent; import com.example.androidsy4.R; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnBindService, btnUnbindService, btnGetStatus; TextView tvServiceStatus; MyService.MyServiceBinder serviceBinder; boolean isServiceBind = false; ServiceConnection conn = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { } @Override public void onServiceDisconnected(componentName name){ } }; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnBindService=findViewById(R.id.btn_main_activity_bind_service); btnUnbindService=findViewById(R.id.btn_main_activity_unbind_service); btnGetStatus=findViewById(R.id.btn_main_activity_get_status); tvServiceStatus=findViewById(R.id.tv_main_activity_service_status); btnBindService.setOnClickListener(this); btnUnbindService.setOnClickListener(this); btnGetStatus.setOnClickListerner(this); } @Override public void onClick(view v){ Intent intent=new Intent(); intent.setClass(MainActivity.this,Myservice.class); switch (v.gerId()){ case R.id.btn_main_activity_bind_service: break; case R.id.btn_main_activity_get_status: break; case R.id.btn_main_activity_unbind_service: break; } } }补充所缺代码
时间: 2024-02-14 11:11:58 浏览: 176
android两个app实现跳转.rar
补充的代码如下:
```
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, MyService.class);
switch (v.getId()) {
case R.id.btn_main_activity_bind_service:
bindService(intent, conn, BIND_AUTO_CREATE);
isServiceBind = true;
break;
case R.id.btn_main_activity_get_status:
if (isServiceBind) {
tvServiceStatus.setText(serviceBinder.getServiceStatus());
} else {
Toast.makeText(MainActivity.this, "请先绑定服务", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_main_activity_unbind_service:
if (isServiceBind) {
unbindService(conn);
isServiceBind = false;
} else {
Toast.makeText(MainActivity.this, "服务未绑定", Toast.LENGTH_SHORT).show();
}
break;
}
}
// 在 onServiceConnected() 中获取服务的 Binder 对象
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceBinder = (MyService.MyServiceBinder) service;
}
// 在 onServiceDisconnected() 中清空 Binder 对象
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBinder = null;
}
```
阅读全文