我有一个homeActivity,其中包含带有操作栏的webview,操作栏的标题是textview
public static TextView mTitleTextView;
并且还有一个接收gcm消息的类
public class GCMNotificationIntentService extends IntentService {
应用收到消息后我想把字符串放到homeActivity的textview中,我试着用
HomeActivity.mTitleTextView.setText("9999999999999999999999999999999999999999999999999999999999");
但是应用程序因错误关闭,我已经阅读了一些旧帖子和Google搜索看到类似广播接收器的东西可以解决这个问题,但我真的不明白它是如何工作的,任何人都可以显示一些实际的源代码,可以应用于我的情况?
答案 0 :(得分:2)
我们可以通过使用handler,broadcat和Listener概念来实现。但我认为广播易于实现和理解,但需要注意或注册和注销广播。
使用LISTENER
创建一个监听器类
public Interface Listener{
public void onResultReceived(String str);
}
现在在下面的活动中实现它
public class MainActivity extends Activity implements listener{
public void onResultReceived(String str){
mTitleTextView.setText(str)
}
}
通过从Activity的oncreate调用服务构造函数来初始化您的Listener
new GCMNotificationIntentService (MainActivity.this);
现在创建服务的公共构造函数,如下所示
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(){
@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)
答案 1 :(得分:0)
使用处理程序并从Intentservice
家长活动:
声明处理程序
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle reply = msg.getData();
// do whatever with the bundle here
}
};
调用intentservice:
Intent intent = new Intent(this, IntentService1.class);
intent.putExtra("messenger", new Messenger(handler));
startService(intent);
Inside IntentService:
Bundle bundle = intent.getExtras();
if (bundle != null) {
Messenger messenger = (Messenger) bundle.get("messenger");
Message msg = Message.obtain();
msg.setData(data); //put the data here
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.i("error", "error");
}
}
或强>
如果您想使用BroadcastReceiver
here就是使用它的好例子。