【问题标题】:Share data between activity and service android在活动和服务android之间共享数据
【发布时间】:2015-04-06 18:30:29
【问题描述】:

我正在做一个 android 应用程序,我想从活动中获取数据到服务 然后该服务将发出通知并将数据发送到另一个活动,用户可以在活动中看到结果?请帮帮我

【问题讨论】:

  • 你试过了吗?
  • 看看这个question
  • 我想先从活动A获取数据到服务S,再发送数据到活动D?

标签: android android-activity service


【解决方案1】:

把这个写在你要发送数据的Activity中:(msg是你要发送的数据)

    Intent myintent = new Intent("package name of class where you want to send");
    myintent.putExtra("message", msg);
    myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//You might need this
    getApplicationContext().sendBroadcast(myintent);

在您的接收器活动的 onCreate() 中: 添加这个:(设置内容视图后的任何地方)

         getApplicationContext().registerReceiver(broadcastReceiver, new IntentFilter("package name of current class i.e receiver"));

在类中添加这个:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
          Log.d(TAG, "Data received is : " +  intent.getStringExtra("message"));
   //Make a Notification here
    }
};

也(在接收器活动中):

  @Override
public void onResume() {
    super.onResume();
    getApplicationContext().registerReceiver(broadcastReceiver, new IntentFilter("package name of current class i.e receiver"));
}

protected void onPause() {
    super.onPause();
    getApplicationContext().unregisterReceiver(broadcastReceiver);
}

【讨论】:

  • 您如何将消息发送到服务?
  • GCM!!处理程序呢?
  • 看看这个question
猜你喜欢
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多