2017-04-15 70 views
0

我已经运行服务(绑定以前successfuly,开始与主要活动unbinded):安卓:无法绑定到正在运行的服务,onServiceConnected不叫

Intent startingIntent = new Intent(this, SturkoPlayerService.class); 
startingIntent.setAction(SturkoPlayerService.PLAYER_START); 
bindService(startingIntent, connection, Context.BIND_AUTO_CREATE); 

当我successfuly接近mainactivity(服务unbinded并保持运行),想重新开启并发出通知意向mainactivity:

Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
intent.putExtra("Service", 1); 
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //tried also another flags 
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

,然后尝试绑定我正在运行的服务

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ... 

    if (getIntent() != null && getIntent().hasExtra("Service")) { 
     if (!bound) { 
      bindService(new Intent(this, SturkoPlayerService.class), connection, 0); 
     } 
    } 
} 

Connection变量的onServiceConnected功能不叫

private ServiceConnection connection = new ServiceConnection() { 
    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
     SturkoPlayerService.LocalBinder mBinder = (SturkoPlayerService.LocalBinder) service; 
     sturkoService = mBinder.getService(); 
     bound = true; 
     sturkoService.registerClient(MainActivity.this); 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     bound = false; 
    } 
}; 

清单:

... 
<activity android:name=".MainActivity" 
    android:screenOrientation="portrait" 
    android:launchMode="singleTask"> //tried other modes too 
    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 

     <category android:name="android.intent.category.LAUNCHER" /> 
    </intent-filter> 
</activity> 

<service 
    android:name=".Service.SturkoPlayerService" 
    android:enabled="true" 
    android:exported="true" 
    android:singleUser="true"> 
</service> 
... 

PS:目录下载并未出现财产以后

+0

“服务未绑定并继续运行” - 除非您调用'startService()',否则服务将不会继续运行。如果您将'bindService()'调用中的'0'更改为'Context.BIND_AUTO_CREATE',并且现在可以正常工作,那么您的问题在于,当您最初解除绑定时,您的服务已被破坏。 – CommonsWare

+0

不,它不是,我的服务一直在运行(它播放声音,我可以听到它)。 当我创建它时,我使用Context.BIND_AUTO_CREATE(第一块代码),我只在重新绑定 – Johnny

+1

时使用0“它播放声音我可以听到它” - 您的服务不播放声音。 Android正在播放声音。仅仅因为你听到声音并不意味着你的服务正在运行。 “当我创建它时,我使用Context.BIND_AUTO_CREATE(第一块代码),我只在重新绑定时使用0” - 我建议你**用'Context.BIND_AUTO_CREATE'替换'0'。如果它现在绑定,那么问题在于,当您最初解除绑定时,您的服务已被破坏,并且您的服务存在错误,导致它无法阻止Android在声音销毁后播放声音。 – CommonsWare

回答

0

服务只会在以下情况下运行:

  • 有1+客户端绑定到它,或

  • 你叫startService()并没有什么已经停止它(例如,stopSelf()stopService()

否则,一旦上次绑定的连接未被绑定,服务停止。