我正在研究服务,我已经编写了一个代码来通过单击按钮绑定服务,通过单击另一个按钮运行服务方法并通过单击第三个按钮解除绑定服务 . 如果我尝试在绑定之前运行服务的方法 . 显然,我得到一条错误消息,而如果我第一次绑定服务,通常会调用该方法 . 问题是,如果我点击第三个按钮取消绑定服务,尽管Unbind(Intent intent)上的服务本机方法给了我一个积极的反馈,我仍然可以从主要活动调用服务方法,就像它应该还是受约束的 .
这是服务代码
package com.antonello.tavolaccio4;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* Created by Antonello on 14/05/2017.
*/
public class Servizio extends Service{
public IBinder binder=new MyBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public boolean onUnbind(Intent intent){
System.out.println("unbinded");
return false;
}
public class MyBinder extends Binder{
Servizio getService(){
return Servizio.this;
}
}
public void metodo(){
System.out.println("Metodo del service");
}
}
这是主要活动代码:
package com.antonello.tavolaccio4;
import android.app.Activity;
import android.app.Service;
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.Button;
public class MainActivity extends Activity {
ServiceConnection serviceConnection;
Servizio servizio;
Button button;
Button button2;
Button button3;
boolean bound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
bindService(intent,serviceConnection, Service.BIND_AUTO_CREATE);
}
});
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
servizio.metodo();
}
});
button3.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(),Servizio.class);
unbindService(serviceConnection);
}
});
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servizio.MyBinder binder=(Servizio.MyBinder)service;
servizio=binder.getService();
bound=true;
System.out.println(bound);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
}
我的 unbindService 方法有什么问题吗?感谢您的任何帮助 .
1 回答
您没有
unbindService()
方法 . 您正在调用从Context
继承的那个 .作为调用
unbindService()
的一部分,您的工作也是设置为null
绑定到绑定连接的任何字段(在您的情况下,servizio
) . 就目前而言,您正在泄漏内存,并且您的服务尝试调用的任何继承方法都可能因为服务被销毁而抛出异常 .