我正在尝试使用 .aidl 文件中定义的 IPC 连接创建服务。
服务启动并且服务连接可以绑定(bind)到它,但是当从同一线程调用 IPC API 时,会导致 NullPointerException
。
当对 IPC API 的调用被放入按钮按下的事件中时,它就会起作用。
如何解决此问题,以便无需按钮事件即可完成调用。
我的主要 Activity
public class MainActivity extends AppCompatActivity {
public final String TAG = "Main Activity";
IMyAidlInterface iMyAidlInterface;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
}
public void onServiceDisconnected(ComponentName className) {
iMyAidlInterface = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent interFaceServiceIntent = new Intent(this, IMyAidlService.class);
bindService(interFaceServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
Intent sigGenIntent = new Intent(this, signalGenerator.class);
startService(sigGenIntent);
Button b = findViewById(R.id.button);
/*
* The following block is what I want to be able to execute. Currently it causes * a NullPointerException
* Caused by: java.lang.NullPointerException: Attempt to invoke interface method * 'int com.aidltest.IMyAidlInterface.getPid()' on a null object reference
*/
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
/*
* The block below using the same interface from within a button event works
* without problem.
*/
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
iMyAidlInterface.getPid();
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
供引用我的 Aidl:
package com.aidltest;
interface IMyAidlInterface {
int getPid();
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
还有我的 list :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aidltest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".IMyAidlService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
最佳答案
发生这种情况是因为 onCreate
调用中的 iMyAidlInterface
为 null
。直到您的连接监听器通过 onServiceConnected
回调您时才会设置它。绑定(bind)是一个异步操作。
关于java - 从主线程调用时,对服务的 IPC 调用会导致 NullPointerException,但不会在按钮事件上调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48310648/