Android - IntentService - 自定义方法的sendBroadcast

时间:2014-07-05 10:09:32

标签: android broadcastreceiver intentservice

我的应用程序中有一个从主线程调用的intent服务。单击按钮后启动意图服务。一旦启动,该服务就会连接到服务器并检索信息。

我希望在检索到数据后向活动发送广播。如果我从onHandleIntent()发送它,可能还没有检索到数据。

我不能从检索数据的方法发送广播吗?如果没有,还有其他选择吗?

代码示例:

onHandleIntent()
{

    myMethod();

  //Here where it is expected to send the broadcast
             Intent broadcastIntent = new Intent();
             broadcastIntent.setAction("com.example.intent.action.MESSAGE_PROCESSED");
             broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
             broadcastIntent.putExtra("TAG",Message);
        getApplicationContext().sendBroadcast(broadcastIntent);

}

MyMethod()
{
 //Retrieving data from server, which returns Message.

 //Here Where I want to send broadcast (Message is ready)
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您还可以使用处理程序/ runnable组合作为计时器,以便在发送广播之前检查该值是否为null。有关如何执行此操作,请参阅this

编辑: 它看起来像这样:

Handler handler = new Handler();
Runnable runnable = new Runnable() {
        public void run() {
            sendBroadcast();
        }
};


onHandleIntent()
{
    myMethod();
    runnable.run();
}

MyMethod()
{
 //Retrieving data from server, which returns Message.

 //Here Where I want to send broadcast (Message is ready)
}


sendBroadcast(){
// If your value is still null, run the runnable again
if (Message == null){
    handler.postDelayed(runnable, 1000);
}
else{
//Here where it is expected to send the broadcast
             Intent broadcastIntent = new Intent();
             broadcastIntent.setAction("com.example.intent.action.MESSAGE_PROCESSED");
             broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
             broadcastIntent.putExtra("TAG",Message);
        getApplicationContext().sendBroadcast(broadcastIntent);
}
}

答案 1 :(得分:0)

您可以在活动类中执行以下操作:

1-创建BroadcastReceiver

private class MyBroadcastReceiver extends BroadcastReceiver             
  @Override    
  public void onReceive(Context context, Intent intent) {


  //Get your server response
  String server_response = intent.getExtras().getString("TAG");

  //Do your work
  }
}

2-在您的活动中创建一个对象(作为活动的成员)

MyBroadcastReceiver mReceiver= new MyBroadcastReceiver ();

3-在onResume()方法中注册,然后使用onPause()方法取消注册。

@Override
public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.example.intent.action.MESSAGE_PROCESSED");

    registerReceiver(mChatReceiver, filter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(mReceiver);
}

这应该足够了!希望它有所帮助!