Activity仍然可以调用unbind服务方法。 这是正常的吗?
我正在学习服务,我已经编写了一个代码,通过单击按钮来绑定服务,通过单击另一个按钮来运行服务的方法,并通过单击第三个按钮来解除绑定服务。 如果我尝试在绑定之前运行服务的方法。 显然,我得到了一条错误消息,而如果我第一次绑定服务,通常会调用该方法。 问题是,如果我点击第三个按钮来取消绑定服务,尽管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方法有什么问题吗? 感谢您的任何帮助。
我的unbindService方法有什么问题吗?
您没有unbindService()
方法。 你正在调用你从Context
继承的那个。
这是你的工作,作为调用unbindService()
,也设置null
绑定到绑定连接的任何字段(在你的情况下, servizio
)。 就目前而言,你正在泄漏内存,你的服务尝试调用的任何继承方法可能会抛出异常,因为服务被破坏。
上一篇: Activity can still call unbind service method. Is it normal?