从 Service 向 Activity 发送简单消息

Posted

技术标签:

【中文标题】从 Service 向 Activity 发送简单消息【英文标题】:Sending a simple message from Service to Activity 【发布时间】:2015-08-18 04:37:50 【问题描述】:

我正在尝试找到一种将整数值从我的服务发送到我的 MainActivity 的方法,但我无法通过互联网上的教程找到它。我正在使用处理程序来接收我从服务中的线程发送的消息。

我在服务中的线程代码:

private class ServiceThread extends Thread 
    @Override
    public void run() 
        super.run();
        try
            Log.i("Service", "TASK PERFORMED");

            int x = 0;
            for (int i = 0; i < 20; i++)
                x += (random.nextInt(20) + 20);
            
            theInteger = x/20;
            Message msg = Message.obtain();
            msg.what = MY_RND_INT;
            msg.arg1 = theInteger;
            handler.sendMessage(msg);
        catch(Exception e)
            e.getMessage();
        
    

我尝试接收消息的代码:

public Messenger mMessenger = new Messenger(new IncomingHandler());


class IncomingHandler extends Handler 
    @Override
    public void handleMessage(Message msg) 
        switch (msg.what) 
            case SimpleService.MY_RND_INT:
                rndInt.setText(msg.arg1);
                break;
            default:
                super.handleMessage(msg);
        
    

【问题讨论】:

@AnixPasBesoin 抱歉,回来晚了!感谢您的回复 【参考方案1】:

你是这样做的:

服务端

// Supposing that your value is an integer declared somewhere as: int myInteger;
private void sendMessage() 
  // The string "my-message" will be used to filer the intent
  Intent intent = new Intent("my-message");
  // Adding some data
  intent.putExtra("my-integer", myInteger);
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

活动端

@Override
public void onResume() 
  super.onResume();
  // This registers messageReceiver to receive messages.
  LocalBroadcastManager.getInstance(this)
                       .registerReceiver(messageReceiver, new IntentFilter("my-message"));


// Handling the received Intents for the "my-integer" event 
private BroadcastReceiver messageReceiver = new BroadcastReceiver() 
  @Override
  public void onReceive(Context context, Intent intent) 
    // Extract data included in the Intent
    int yourInteger = intent.getIntExtra("my-integer", -1); // -1 is going to be used as the default value
  
;
    
@Override
protected void onPause() 
  // Unregister since the activity is not visible
  LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
  super.onPause();

【讨论】:

嗨,我尝试使用此代码,但是当我使用 sendMessage() 时,应用程序崩溃了。接收方需要注册吗? @user1527152 是的。检查我提供的示例代码和答案。 如果不在同一个包里怎么办?

以上是关于从 Service 向 Activity 发送简单消息的主要内容,如果未能解决你的问题,请参考以下文章

如何将数据从活动传递到正在运行的服务

从 Activity 向服务发送消息 - Android

Android开发学习之路-回调实现Service向activity传递数据

从 Host Activity 向 Fragments 发送位置更新

从一个活动向另一个活动发送消息[重复]

如何从后台service传递数据到前台正在运行的activity