2016-11-24 95 views
0

我一直在寻找这个很长一段时间,但我无法修复试图访问空对象上的ResolveInfo.serviceInfo时引发的空指针异常。 (在启动服务为API 20时,作出明确的意图)无法绑定服务Android()

这里是.aidl接口:

package com.example.playerclient; 

interface AIDLinterface { 
    void Play_Clip(int id); 
    void Pause_Playback(); 
    void Resume_Playback(); 
    void Stop_Player(); 
} 

下面是相关的客户端代码(onResume()是在NPE被抛出)

public class PlayerClientMain extends AppCompatActivity 
{ 

    Button button; 
    private AIDLinterface mAIDLinterface; 
    private boolean mIsBound = false; 

    private ServiceConnection mServiceConn = new ServiceConnection() 
    { 

     @Override 
     public void onServiceConnected(ComponentName componentName, IBinder iservice) 
     { 
      Log.v("SERVICE CONNECTED", "SERVICE CONNECTED"); 
      mAIDLinterface = AIDLinterface.Stub.asInterface(iservice); 

      Toast.makeText(getApplicationContext(), "service connected", Toast.LENGTH_SHORT).show(); 

      mIsBound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName componentName) 
     { 
      Log.v("SERVICE DISCONNECTED", "SERVICE DISCONNECTED"); 
      mAIDLinterface = null; 
      Toast.makeText(getApplicationContext(), "service disconnected", Toast.LENGTH_SHORT).show(); 
      mIsBound = false; 

     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_player_client_main); 
     button = (Button) findViewById(R.id.button); 
    } 


    @Override 
    protected void onResume() 
    { 
     super.onResume(); 

     if (!mIsBound) 
     { 
      boolean b = false; 
      Intent i = new Intent(AIDLinterface.class.getName()); 

      ResolveInfo info = getPackageManager().resolveService(i, Context.BIND_AUTO_CREATE); //this is always null 
      i.setComponent(new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name)); //NPE because info is null 

      b = bindService(i, this.mServiceConn, Context.BIND_AUTO_CREATE); 

      if (b) 
       Log.i("SUCCESS:", "bindService() success!"); 
      else 
       Log.i("FAILURE:", "bindService() failed!"); 
     } 
    } 
} 

服务代码不相关,因为无论如何我都无法到达bindService()行。有任何想法吗?

回答

0

我认为问题在于创建意图本身。

假设AIDLinterface.class是服务类,你应该建立这样的意图:

Intent i = new Intent(this, AIDLinterface.class); 

有关详细信息,请参阅https://developer.android.com/guide/components/services.html

干杯〜

+0

AIDLinterface不是服务类。它是允许远程服务与我的本地客户端(PlayerClient)通信的接口。 – user3487243

+0

谢谢你的回答,但这没有帮助。我不再获得NPE,但bindService()返回false – user3487243