从服务更新活动中的文本视图标题 [英] update textview title in an Activity from a service
问题描述
我有一个 homeActivity,其中包含一个带有操作栏的 webview,操作栏的标题是一个 textview
i have an homeActivity which contains a webview with an actionbar, the title of the actionbar is an textview
public static TextView mTitleTextView;
还有一个接收gcm消息的类
and also has an class which do receive gcm message
public class GCMNotificationIntentService extends IntentService {
应用收到消息后我想把字符串放到homeActivity的textview中,我尝试使用
after the app received a message i want to put the string to the textview of homeActivity, i tried to use
HomeActivity.mTitleTextView.setText("9999999999999999999999999999999999999999999999999999999999");
但是应用程序关闭时出现错误,我读过一些旧帖子并在谷歌上看到类似广播接收器的东西可以解决这个问题,但我不太明白它是如何工作的,任何人都可以展示一些可以应用的实际源代码我的情况?
but the app shutdown with error, i've read some old post and googled see something like broadcast receiver can solve this problem, but i not really understand how it works, can anyone show some actually source code which can be applied in my situation?
推荐答案
我们可以通过使用 handler,broadcat 和 Listener 的概念来实现.但是我认为广播很容易实现和理解但需要注意或注册和注销广播.
We can achieve by using handler,broadcat and Listener concept.But I think broadcast is easy to implement and understand but need to take care or register and unregister of broadcast.
使用监听器
创建监听器类
public Interface Listener{
public void onResultReceived(String str);
}
现在在如下活动中实现它
Now implement it in activity like below
public class MainActivity extends Activity implements listener{
public void onResultReceived(String str){
mTitleTextView.setText(str)
}
}
通过从 Activity 的 oncreate 调用服务的构造函数来初始化你的监听器
Initialize your Listener by calling constructor of service from oncreate of Activity
new GCMNotificationIntentService (MainActivity.this);
现在创建您的服务的公共构造函数,如下所示
Now create public constructor of your service like below
public class GCMNotificationIntentService extends IntentService {
public static Listener listener_obj;
public GCMNotificationIntentService (Listener listener)
{
listener_obj=listener;
}
Listener.onResultReceived("99999999999999999999999999999999999999999");
//send the data which should be shown on textview
使用广播
registerReceiver( mMessageReceiver, new IntentFilter("GETDATA"));
//register localbraodcast with receiver object and intent filter inside oncreate
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String str= intent.getStringExtra("DATA", "No Data");
mTitleTextView.setText(str);
}
};
ondestroy()
{
unregisterReceiver( mMessageReceiver);
}
从服务发送数据
Intent intent = new Intent("GETDATA");
intent.putExtra("DATA", "9999999");
sendBroadcast(intent)
这篇关于从服务更新活动中的文本视图标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!