首页 \ 问答 \ 修订2:如何将数据从后台服务/线程传递到除创建后台服务的MainActivity之外的其他活动(Revision 2: How to pass data from a background Service/thread to some other activity than the MainActivity that created the background service)

修订2:如何将数据从后台服务/线程传递到除创建后台服务的MainActivity之外的其他活动(Revision 2: How to pass data from a background Service/thread to some other activity than the MainActivity that created the background service)

我创建了一个简单的Android应用程序,用于测试如何使用处理程序或处理程序将数据从后台服务/线程传递到除创建后台服务的MainActivity之外的其他活动 。 我有Service,Thread和一个在MainActivity中工作的处理程序。 最后一步是获取一个处理程序将数据传递给除MainActivity之外的其他活动 。 我可以让服务将消息传递给MainActivity的处理程序,但我不知道如何让它将数据传递给其他某个活动

为什么有人想要这样做? 我认为这与一个简单的MP3播放器相比,但它实际上是一个很好的FM收音机。 MainActivity使用后台服务,允许我选择一个FM电台。 当我启动Play活动时,它应该绑定到相同的后台服务,以便我可以继续收听,而它(好的部分)显示图形均衡器或音频动画。 基本上,我不知道如何绑定到来自多个活动的后台服务。

我的代码最初基于Pro Android 2中的服务示例页面304,并且受到了CommonsWare示例应用程序的巨大帮助。

请看看我目前的代码。 它由三个仔细评论的文件组成,这些文件描述了我正在尝试做的事情以及我将数据传递给除MainActivity之外的其他一些活动的困难:

/**************************************************************************************************
 * File: MainActivity.java
 * Application: BackgroundService
 * Description: This file contains the main activity that is run when the BackgroundService
 *     application is launched.
 **************************************************************************************************/

package com.marie.mainactivity;

import com.marie.mainactivity.BackgroundService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/*
 * Class: MainActivity
 * Purpose: Using a button, the MainActivity class starts the backgroundService and
 *     the RcvMessages activity. Using another button MainActivity stops the backgroundService.
 *     NOTE: RcvMessages is only a stub that does nothing but display a simple message.
 * Handler: MainActivity defines and provides a reference to "handler" for the backgroundService.
 */
public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.d(TAG, "starting service");

        /*
         * The bind button: bindBtn
         * Clicking this button starts the background Service and launches the
         * RcvMessages activity. NOTE: RcvMessages is only a stub so far.
         */
        Button bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Start the background Service for sending canned messages to the handler as a test.
                Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
                backgroundService.putExtra(BackgroundService.EXTRA_MESSENGER, new Messenger(handler));
                startService(backgroundService);

                // Start the RcvMessages activity to receive messages from the handler. But how???
                Intent messages = new Intent(MainActivity.this, com.marie.mainactivity.RcvMessages.class);
                startActivity(messages);
            }
        });

        /*
         * The unbind button: unbindBtn
         * Clicking this button stops the background Service.
         */
        Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Stop the background Service
                Intent backgroundService = new Intent(MainActivity.this, BackgroundService.class);
                stopService(backgroundService);
            }
        });
    }

    /*
     * This is the handler to be passed to the background Service via a Messenger.
     * NOTE: I want it to send messages to my RcvMessages activity.
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // simple handler test (does not send messages to RcvMessages activity
            String obj = (String) msg.obj;
            Log.i("handleMessge", "obj: " + obj);  
        }
    };
}

/**************************************************************************************************
 * File: BackgroundService.java
 * Application: BackgroundService
 * Description: This file contains the background Service that is launched by the MainActivity's
 *     bind button.
 **************************************************************************************************/

package com.marie.mainactivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

/*
 * Class: BackgroundService
 * Purpose: Using the onStart() method the BackgroundService gets the reference to the
 *     Messenger instance that was passed to BackgroundService. The messenger is then
 *     used by the ServiceWorker() thread to send messages to the handler that is defined
 *     in the MainActivity class.
 */
public class BackgroundService extends Service {
    private NotificationManager notificationMgr;

    public static final String EXTRA_MESSENGER = "com.marie.mainactivity.EXTRA_MESSENGER";
    private Messenger messenger;

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

        notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        displayNotificationMessage("starting Background Service");

        Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
        thr.start();
    }   

    /*
     * This is the ServiceWorker thread that passes messages to the handler defined in
     * the MainActivity class.
     * NOTE: Instead of passing messages to a handler in MainActivity I would like
     * it to pass messages to a handler defined in the RcvMessages activity.
     */
    class ServiceWorker implements Runnable
    {
        public void run() {
            // do background processing here... something simple

            // send a message to the handler defined in the MainActivity class
            try {
                Message msg1 = Message.obtain();
                msg1.obj = "Hello 1";
                messenger.send(msg1);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            // stop the service when done...
            // BackgroundService.this.stopSelf();
            // Or use the unbindBtn in the MainActivity class.
        }
    }

    @Override
    public void onDestroy()
    {
        displayNotificationMessage("stopping Background Service");
        super.onDestroy();
    }

    /*
     * onStart is where we get our reference the Messenger that allows
     * us to send messages to the handler defined in the MainActivity class.
     */
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        Bundle extras = intent.getExtras();
        messenger = (Messenger)extras.get(EXTRA_MESSENGER);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void displayNotificationMessage(String message)
    {
        Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        notification.setLatestEventInfo(this, "Background Service", message, contentIntent);

        notificationMgr.notify(R.id.app_notification_id, notification);
    }
}

/**************************************************************************************************
 * File: RcvMessages.java
 * Application: BackgroundService
 * Description: This file contains stub code that displays a test message in an EditText.
 **************************************************************************************************/

package com.marie.mainactivity;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;

/*
 * Class: RcvMessages
 * Purpose: RcvMessages is stub code that I want to extend in some way to receive messages from
 *     the background Service.
 *     NOTE: I don't know who to do this.
 */
public class RcvMessages extends Activity {

    EditText myText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.messages);

        myText = (EditText)findViewById(R.id.my_text);

        myText.setSingleLine();
        myText.setInputType(InputType.TYPE_NULL);

        // Display a simple test message for now.
        myText.setText("RcvMessages here");
    }
}

任何帮助使用后台服务,线程和处理程序将数据传递给除了创建backgraound服务的MainActivity之外的其他活动将不胜感激。


I've created a simple Android application for testing how to use a handler or handlers to pass data from a background Service/thread to some other activity other than the MainActivity that created the background service. I've got the Service, thread, and a handler working in the MainActivity. The last step is to get a handler to pass data to some other activity other than the MainActivity. I can get the Service to pass messages to the MainActivity's handler, but I don't know how to get it to pass data to some other activity.

Why would anyone want to do this? I thought this compared to a simple MP3 player, but what it actually compares to is a nice FM radio. The MainActivity uses a background Service that allows me to select an FM station. When I launch the Play activity it should bind to the same background Service so I can continue to listen while it (the nice part) displays a graphic equalizer or animation of the the audio. Basically, I don't know how to bind to the background Service from more than one activity.

My code was originally based on a Service example page 304 in Pro Android 2 and was helped tremendously by a CommonsWare Sample Application.

Please have a look at my current code. It consists of three carefully commented files that describe what I am trying to do and the difficulties I am having passing data to some other activity in addition to the MainActivity:

/**************************************************************************************************
 * File: MainActivity.java
 * Application: BackgroundService
 * Description: This file contains the main activity that is run when the BackgroundService
 *     application is launched.
 **************************************************************************************************/

package com.marie.mainactivity;

import com.marie.mainactivity.BackgroundService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/*
 * Class: MainActivity
 * Purpose: Using a button, the MainActivity class starts the backgroundService and
 *     the RcvMessages activity. Using another button MainActivity stops the backgroundService.
 *     NOTE: RcvMessages is only a stub that does nothing but display a simple message.
 * Handler: MainActivity defines and provides a reference to "handler" for the backgroundService.
 */
public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.d(TAG, "starting service");

        /*
         * The bind button: bindBtn
         * Clicking this button starts the background Service and launches the
         * RcvMessages activity. NOTE: RcvMessages is only a stub so far.
         */
        Button bindBtn = (Button)findViewById(R.id.bindBtn);
        bindBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Start the background Service for sending canned messages to the handler as a test.
                Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
                backgroundService.putExtra(BackgroundService.EXTRA_MESSENGER, new Messenger(handler));
                startService(backgroundService);

                // Start the RcvMessages activity to receive messages from the handler. But how???
                Intent messages = new Intent(MainActivity.this, com.marie.mainactivity.RcvMessages.class);
                startActivity(messages);
            }
        });

        /*
         * The unbind button: unbindBtn
         * Clicking this button stops the background Service.
         */
        Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
        unbindBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                // Stop the background Service
                Intent backgroundService = new Intent(MainActivity.this, BackgroundService.class);
                stopService(backgroundService);
            }
        });
    }

    /*
     * This is the handler to be passed to the background Service via a Messenger.
     * NOTE: I want it to send messages to my RcvMessages activity.
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // simple handler test (does not send messages to RcvMessages activity
            String obj = (String) msg.obj;
            Log.i("handleMessge", "obj: " + obj);  
        }
    };
}

/**************************************************************************************************
 * File: BackgroundService.java
 * Application: BackgroundService
 * Description: This file contains the background Service that is launched by the MainActivity's
 *     bind button.
 **************************************************************************************************/

package com.marie.mainactivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

/*
 * Class: BackgroundService
 * Purpose: Using the onStart() method the BackgroundService gets the reference to the
 *     Messenger instance that was passed to BackgroundService. The messenger is then
 *     used by the ServiceWorker() thread to send messages to the handler that is defined
 *     in the MainActivity class.
 */
public class BackgroundService extends Service {
    private NotificationManager notificationMgr;

    public static final String EXTRA_MESSENGER = "com.marie.mainactivity.EXTRA_MESSENGER";
    private Messenger messenger;

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

        notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        displayNotificationMessage("starting Background Service");

        Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
        thr.start();
    }   

    /*
     * This is the ServiceWorker thread that passes messages to the handler defined in
     * the MainActivity class.
     * NOTE: Instead of passing messages to a handler in MainActivity I would like
     * it to pass messages to a handler defined in the RcvMessages activity.
     */
    class ServiceWorker implements Runnable
    {
        public void run() {
            // do background processing here... something simple

            // send a message to the handler defined in the MainActivity class
            try {
                Message msg1 = Message.obtain();
                msg1.obj = "Hello 1";
                messenger.send(msg1);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            // stop the service when done...
            // BackgroundService.this.stopSelf();
            // Or use the unbindBtn in the MainActivity class.
        }
    }

    @Override
    public void onDestroy()
    {
        displayNotificationMessage("stopping Background Service");
        super.onDestroy();
    }

    /*
     * onStart is where we get our reference the Messenger that allows
     * us to send messages to the handler defined in the MainActivity class.
     */
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        Bundle extras = intent.getExtras();
        messenger = (Messenger)extras.get(EXTRA_MESSENGER);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void displayNotificationMessage(String message)
    {
        Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

        notification.setLatestEventInfo(this, "Background Service", message, contentIntent);

        notificationMgr.notify(R.id.app_notification_id, notification);
    }
}

/**************************************************************************************************
 * File: RcvMessages.java
 * Application: BackgroundService
 * Description: This file contains stub code that displays a test message in an EditText.
 **************************************************************************************************/

package com.marie.mainactivity;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;

/*
 * Class: RcvMessages
 * Purpose: RcvMessages is stub code that I want to extend in some way to receive messages from
 *     the background Service.
 *     NOTE: I don't know who to do this.
 */
public class RcvMessages extends Activity {

    EditText myText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.messages);

        myText = (EditText)findViewById(R.id.my_text);

        myText.setSingleLine();
        myText.setInputType(InputType.TYPE_NULL);

        // Display a simple test message for now.
        myText.setText("RcvMessages here");
    }
}

Any help using a background Service, thread, and handler(s) to pass data to some other activity in addition to the MainActivity that created the backgraound Service would be greatly appreciated.


原文:https://stackoverflow.com/questions/6352244
更新时间:2022-08-01 14:08

最满意答案

put across 使...被接受,解释清楚
put away把...收起,放好
put down记下
put forward 提出...
put in插话
put into practice实施,实行
put off推迟
put on 穿上 
put out 伸出,熄灭
put to use使用,利用
put up 举起,张贴 
put up with 容忍
应该还会有的,我知道的就只有这些了,希望能帮你忙哈。。。你也可以上百度去搜索一些

相关问答

更多
  • 基本一样,略有差别,虽然2者后都接名词.但意思不一样,举个例,put the book into your school bag,就比说成put the book in要好些 put in v. 放进, 提出, 提交, 插入, 进入, 使就职, 种植, 进港 To interpose: 插入,插话: He put in a good word for me. 他插进来为我说了一句好话 To spend (time) at a location or job: 花时间:在某一场所或工作上花费(时间): The ...
  • 第一个是应用;靠岸,第二个是提交;提出;放入;种植,第三个是使进入;把...放进,第四的是穿上;上演;增加;假装。希望采纳
  • 被动语态,不就是 be + 过去分词,也就是 be purpose into... 吗? been put into... 只有在完成时中的被动语态结构,但是此句是一般现在时,所以只需要 be put into 即可
  • Put up 提供;建造;举起;推举,提名;供给…住宿 put someone up留宿某人;为某人提供住宿 put up安装 put you up table摆你上台 Put on 穿上;上演;增加;假装;使…上场 put-on假装;做作的 put money on打赌 put…on增加 Get on 上车,上马;进展,使前进 上车,上马;进展,使前进 start a project, mount the horse get hooked on sth被某事迷住了 get dependent on依靠 g ...
  • put about 散布(消息);宣称 put across 解释;表达 put aside 节省(钱、时间);储蓄;储存…备用 put away 储存(钱);储存…备用;储蓄 (= put by) 吃掉;喝掉 put back 拨回;向后移 put by 储蓄;储存…备用;储存(钱) put down 写下;记下 put down as 视为;看作 put down for 把(某人)列入(捐款人)名单 put down to 说…因(某事)而起 put forward 提出(意见、建议) put in ...
  • put on 穿上、、、、 put out 熄灭;关熄;扑灭 put through 接通电话 put to 问(问题);提(建议) 用某种方式试验(某物或某人) put together 商量 put about 散布(消息);宣称 put across 解释;表达 put aside 节省(钱、时间);储蓄;储存…备用 put away 储存(钱);储存…备用;储蓄 (= put by) 吃掉;喝掉 put back 拨回;向后移 推迟;延期;搁置;拖延 put back 拨回;向后移 to put b ...
  • put 就是入栈 set 就是设置值 get 就是取值
  • put across 使...被接受,解释清楚 put away把...收起,放好 put down记下 put forward 提出... put in插话 put into practice实施,实行 put off推迟 put on 穿上 put out 伸出,熄灭 put to use使用,利用 put up 举起,张贴 put up with 容忍 应该还会有的,我知道的就只有这些了,希望能帮你忙哈。。。你也可以上百度去搜索一些
  • Ajax以异步方式运行(这是其名称的一部分)。 这意味着对$.ajax的两次调用可能无法以任何顺序完成 - 或者永远完成。 如果您的代码依赖于异步调用的结果,那么依赖于调用的所有工作都需要在ajax的回调中完成。 在ajax完成后触发回调。 您可以使用success ,或使用延迟(内置): $.ajax(putRequest).done(function () { $.ajax(getRequest); }); Ajax runs asynchronously (that's part of it ...
  • 用这一行替换警报: document.getElementsByClassName('textbox')[1].value=text // 1. You need to get the // document.getElementsByClassName('textbox') // 2. This will return an array, you need the second Element [2] // .value=text replace the ...

相关文章

更多

最新问答

更多
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何使用自由职业者帐户登录我的php网站?(How can I login into my php website using freelancer account? [closed])
  • SQL Server 2014版本支持的最大数据库数(Maximum number of databases supported by SQL Server 2014 editions)
  • 我如何获得DynamicJasper 3.1.2(或更高版本)的Maven仓库?(How do I get the maven repository for DynamicJasper 3.1.2 (or higher)?)
  • 以编程方式创建UITableView(Creating a UITableView Programmatically)
  • 如何打破按钮上的生命周期循环(How to break do-while loop on button)
  • C#使用EF访问MVC上的部分类的自定义属性(C# access custom attributes of a partial class on MVC with EF)
  • 如何获得facebook app的publish_stream权限?(How to get publish_stream permissions for facebook app?)
  • 如何防止调用冗余函数的postgres视图(how to prevent postgres views calling redundant functions)
  • Sql Server在欧洲获取当前日期时间(Sql Server get current date time in Europe)
  • 设置kotlin扩展名(Setting a kotlin extension)
  • 如何并排放置两个元件?(How to position two elements side by side?)
  • 如何在vim中启用python3?(How to enable python3 in vim?)
  • 在MySQL和/或多列中使用多个表用于Rails应用程序(Using multiple tables in MySQL and/or multiple columns for a Rails application)
  • 如何隐藏谷歌地图上的登录按钮?(How to hide the Sign in button from Google maps?)
  • Mysql左连接旋转90°表(Mysql Left join rotate 90° table)
  • dedecms如何安装?
  • 在哪儿学计算机最好?
  • 学php哪个的书 最好,本人菜鸟
  • 触摸时不要突出显示表格视图行(Do not highlight table view row when touched)
  • 如何覆盖错误堆栈getter(How to override Error stack getter)
  • 带有ImageMagick和许多图像的GIF动画(GIF animation with ImageMagick and many images)
  • USSD INTERFACE - > java web应用程序通信(USSD INTERFACE -> java web app communication)
  • 电脑高中毕业学习去哪里培训
  • 正则表达式验证SMTP响应(Regex to validate SMTP Responses)