android.app.ServiceConnectionLeaked:Activity ... MainActivity泄露了ServiceConnection ... MainActivity $ 1 @ e794142最初绑定在这里

时间:2016-02-24 13:27:31

标签: java android

失败的@下线 -

boolean isAMatch = Character.toString(ch).matches("[A-Za-z01]")

以下是追踪......

bindService(intent, m_serviceConnection, Context.BIND_AUTO_CREATE);

MainActivity.class

Activity com.example.alwaysrunningprocesswithcallanswertap.MainActivity has leaked ServiceConnection com.example.alwaysrunningprocesswithcallanswertap.MainActivity$1@e794142 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.alwaysrunningprocesswithcallanswertap.MainActivity has leaked ServiceConnection com.example.alwaysrunningprocesswithcallanswertap.MainActivity$1@e794142 that was originally bound here
    at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
    at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
    at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
    at android.app.ContextImpl.bindService(ContextImpl.java:1757)
    at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
    at com.example.alwaysrunningprocesswithcallanswertap.MainActivity.onCreate(MainActivity.java:48)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)   
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

3 个答案:

答案 0 :(得分:15)

您需要在代码中添加此内容。

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(m_serviceConnection);
    Toast.makeText(MainActivity.this, "Service Un-Binded", Toast.LENGTH_LONG).show();
};

答案 1 :(得分:0)

另一种好的做法是添加一个标志,以了解何时添加了服务。

List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
List<String> copyList = new ArrayList<String>(); 
Consumer<String> consumer = s->copyList.add(s);
list.stream().forEach(consumer);

如果您在应用程序生命周期的不同阶段中绑定和取消绑定服务,这将非常有用。

答案 2 :(得分:0)

onStop()

是您可以在活动中取消绑定服务的另一个位置。

  

当您想与   仅当您的活动处于前台时才提供服务。 See official Android Developer guide suggestion

Override
protected void onStop() {
   super.onStop();
   unbindService(m_serviceConnection);
};

在这种情况下,绑定服务的首选方法是在Activity的onStart()方法中。