Android使用sendOrderedBroadcast从服务发送数据

时间:2015-02-13 05:21:02

标签: android

我正在尝试将sendOrderedBroadcast的数据发送到BroadcastListener,例如:

public class ServiceReceiveSubjects extends IntentService {
    public static String RECEIVE_SERVER_DATA = "ServiceReceiveNewSubject";

    public ServiceReceiveSubjects() {
        super("ServiceReceiveSubject");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        receive();
    }

    private void receive() {
        String jsonStr = "DATA";
        NotifyMsg( jsonStr );
    }
    private void NotifyMsg( String data) {
        Intent intent = new Intent(M.ACTION_BROADCAST_RECEIVE_SUBJECT_REFRESH);
        intent.putExtra(RECEIVE_SERVER_DATA, data);
        sendOrderedBroadcast(intent, null);
    }
}

现在我希望在活动中将这个putExtra数据与boardcast一起使用:

final BroadcastReceiver NotifyReceivePostsRefresh = new BroadcastReceiver() {
    @Override
    public void onReceive(Context ctxt, Intent i) {
        if (G.currentActivity.getIntent().getExtras() != null) {
            Bundle extras = G.currentActivity.getIntent().getExtras ();
            Log.e("JSON: ",extras);
        }
    }
};

不幸的是,null变量

获得了extras

1 个答案:

答案 0 :(得分:1)

使用在onReceive中作为参数接收的Intent来获取sendOrderedBroadcast发出的值:

    @Override
    public void onReceive(Context ctxt, Intent i) {
        if (i.getExtras() != null) {
            Bundle extras = i.getExtras();
        }
    }
  

很遗憾,我为extras变量

获取null

您在Intent中发送键值而不是Bundle,因此只需使用i.getStringExtra获取值:

 if (i!= null) {
     String strData = i.getStringExtra(ServiceReceiveSubjects.RECEIVE_SERVER_DATA);
     Log.e("JSON: ",strData);
   }