3

我想从“class gps_Listener”创建“Intent”并在“class LocationChangedReceiver”中发送参数

我的班级 gps_Listener

public class gps_Listener implements LocationListener {

        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            send("I found the location");

        }

        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        public void send(String str) {
            Intent intent = new Intent("logGPS");
            intent.putExtra("Message", str);
            sendBroadcast(intent);   //-  without context does not work

        }


    }

和类 LocationChangedReceiver

public class LocationChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

    }

}

我不知道该怎么做,因为你可以看到没有“上下文”

4

1 回答 1

3

您可以在创建时将上下文传递给您的侦听器。所以你可以在你的发送方法中使用它:

public class gps_Listener implements LocationListener {
    private Context context;

    public gps_Listener(Context context) {
        this.context = context;
    }

    ...

    public void send(String str) {
        Intent intent = new Intent("com.your.package.YOUR_ACTION");
        intent.putExtra("Message", str);
        context.sendBroadcast(intent);
    }
}

以这种方式创建它:

gps_Listener myListener = new gps_Listener(yourContext);
LocationManager myManager = (LocationManager)getSystemService(LOCATION_SERVICE);
myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myListener);

请记住在清单中注册您的广播接收器(您也可以动态取消/注册):

<receiver android:name=".receivers.LocationChangedReceiver" android:enabled="true">
   <intent-filter>
       <action android:name="com.your.package.YOUR_ACTION"></action>
   </intent-filter>
</receiver>
于 2012-10-03T07:05:50.047 回答