其他分享
首页 > 其他分享> > 我无法配置Intent和BroadcastReceiver

我无法配置Intent和BroadcastReceiver

作者:互联网

我想从“类gps_Listener”创建“ Intent”并在“类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

    }

}

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

解决方法:

您可以在创建上下文时将其传递给您的侦听器.
因此,您可以在send方法中使用它:

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>

标签:android-intent,broadcastreceiver,android
来源: https://codeday.me/bug/20191127/2075161.html