Emulate a broadcast in Android

2019-02-14 12:00发布

问题:

I need to know how to emulate a broadcastreceiver.

I have the following code, but I have no clue how to actually see when it is receiving a broadcast.

public class LocationBroadcastReceiver extends BroadcastReceiver 
{
@Override

public void onReceive(Context context, Intent intent) {


    Bundle b = intent.getExtras();
    Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);

    Toast.makeText(context, loc.toString(), Toast.LENGTH_SHORT).show(); 
    Log.d("com.dennis.test","LOCATION:  " + loc.toString());


}
}

In my manifest I have the following:

<receiver android:name="com.dennis.test.LocationBroadcastReceiver">
    <intent-filter>
        <action android:name="android.location.LocationManager.KEY_LOCATION_CHANGED" />
    </intent-filter>
</receiver>

回答1:

Go to the folder where your android-sdk is installed and then to platform-tools. There will be some executables. One of them is 'adb'.

When in the folder, execute

./adb shell am broadcast -a android.intent.action.KEY_LOCATION_CHANGED -c android.intent.category.HOME -n com.dennis.test/.LocationBroadcastReceiver

or on windows

adb shell am broadcast -a android.intent.action.KEY_LOCATION_CHANGED -c android.intent.category.HOME -n com.dennis.test/.LocationBroadcastReceiver



回答2:

You should also be able to use MockLocation to generate from your executable or a JUnit. I have not used it, but that is its purpose.

It is probably functionally similar to @user1258903's answer, but should be able to send far away locations (i.e., the North Pole, mom's house, bottom of the ocean, etc.) That way you can test out your computations and maps integration, etc. that you might have.

How to emulate GPS location in the Android Emulator?