繁体   English   中英

如何在仪器内部注册广播接收机?

[英]How to register broadcast receiver inside instrumentation?

我正在尝试通过以android junitRunner运行的apk获取蓝牙发现结果。 一切正常,但在registerReciever时出现错误。 可能是什么原因 ?

java.lang.SecurityException:给定的调用者程序包com.ex.test在进程ProcessRecord中未运行{d740580 19462:com.ex / u0a302}

码-

@Test
public void demo() throws Exception {

    Context ctx = InstrumentationRegistry.getInstrumentation().getContext();
    BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBtAdapter.isDiscovering()) {
        System.out.println("Stop ongoing discovery");
        mBtAdapter.cancelDiscovery();
    }
    System.out.println("Start fresh discovery");
    mBtAdapter.startDiscovery();

    DisciveryRecv dReceiver = new DisciveryRecv ();
    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    ctx.registerReceiver(dReceiver, filter);
}


public class DisciveryRecv extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction(); 
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String dev = device.getName() + " - " + device.getAddress();
            mUtils.log("Found: " + dev);
        }
    }
}

startDiscovery可以正常工作,但是在ctx.registerReceiver(dReceiver, filter); ,应用抛出异常。

仪器cmd-

亚行外壳工具-w -r -e debug false -e类com.ex.main#demo com.ex / android.support.test.runner.AndroidJUnitRunner

InstrumentationRegistry.getTargetContext()返回被测应用程序的上下文。

InstrumentationRegistry.getContext()返回运行测试的Instrumentation的上下文。

然后,如果您要像描述的情况一样注册接收者,则需要应用程序上下文。 但是,这并不是真正在测试您的应用程序是否接收广播,因为接收者不是您的应用程序的一部分。

无论如何,回答第二个问题,使用InstrumentationRegistry.getContext()的原因是,当您的测试需要访问不属于应用程序但仅在测试中使用的资源或文件时。

编辑

这里有一个例子。 两个文件,一个在应用程序中,另一个在测试中

src/androidTest/assets/sometestfile
src/main/assets/someappfile

然后您可以根据上下文访问它们

@Test
public final void testAccessToAppAssetsFromTest() throws IOException {
    final AssetManager assetManager = mInstrumentation.getTargetContext().getAssets();
    assetManager.open("someappfile");
}

@Test
public final void testAccessToTestAssetsFromTest() throws IOException {
    final AssetManager assetManager = mInstrumentation.getContext().getAssets();
    assetManager.open("sometestfile");
}

如果尝试相反的操作,则测试将失败。

我已经找到答案了。 使用InstrumentationRegistry.getTargetContext()解决了我的问题。

InstrumentationRegistry.getInstrumentation() ,返回当前正在运行的Instrumentation。

InstrumentationRegistry.getContext() ,返回此Instrumentation包的上下文。

InstrumentationRegistry.getTargetContext() ,返回目标应用程序的应用程序上下文。

这是一些信息-https ://developer.android.com/reference/android/support/test/InstrumentationRegistry.html#getTargetContext()

但是我仍然不确定何时使用InstrumentationRegistry.getContext() ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM