我已经看了很久了,但是我无法修复在尝试访问null对象上的ResolveInfo.serviceInfo
时抛出的Null Pointer Exception。 (从API 20开始服务时必须明确意图)
这是.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 :(得分:0)
我认为问题在于创建意图本身。
假设AIDLinterface.class
是服务类,您应该像这样创建意图:
Intent i = new Intent(this, AIDLinterface.class);
有关详细信息,请参阅https://developer.android.com/guide/components/services.html
干杯〜