2015-04-06 92 views
-4

我正在做一个android应用程序,我想从活动中获取数据到服务 ,然后此服务将发出通知并将数据发送到其他活动,用户可以看到结果活动?请HEP我在活动和服务之间共享数据android

+3

你还尝试过什么吗? – FWeigl

+0

看看这个[问题](http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging) –

+0

我想首先从活动A获取数据到服务S并将数据发送到活动D? –

回答

0

写在活动从那里你要发送的数据:(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); 
} 
+0

你是如何发送消息到服务的? –

+0

GCM !! Handler怎么样? –

+0

看看这[问题](http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging) –