修订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
最满意答案
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 容忍 应该还会有的,我知道的就只有这些了,希望能帮你忙哈。。。你也可以上百度去搜索一些
相关问答
更多-
put into 、put in 意思[2022-05-31]
基本一样,略有差别,虽然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 ... -
急!put to,put in,put into,put on的区别~[2022-07-01]
第一个是应用;靠岸,第二个是提交;提出;放入;种植,第三个是使进入;把...放进,第四的是穿上;上演;增加;假装。希望采纳 -
这里句子用put into还是been put into?[2022-09-29]
被动语态,不就是 be + 过去分词,也就是 be purpose into... 吗? been put into... 只有在完成时中的被动语态结构,但是此句是一般现在时,所以只需要 be put into 即可 -
put up和 put on get up 和get on的区别[2023-02-07]
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 get give look的短语有哪些啊?还有它们的意思.Thank you.[2022-10-30]
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和get的相关短语!越多越好,中文解释详细一点!谢谢[2023-08-04]
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的所有短语[2023-06-07]
put 就是入栈 set 就是设置值 get 就是取值 -
有什么put 的组成短语?比如 PUT OFF什么的[2023-12-13]
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 PUT和GET(PUT and GET with $.ajax)[2022-08-28]
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 ...