我有一个包含与动作条网页视图的homeActivity,所述动作条的标题是一个TextView的
public static TextView mTitleTextView;
并且也有一个类做接收GCM消息
public class GCMNotificationIntentService extends IntentService {
该应用程序接收到的消息我想把字符串homeActivity的TextView的后,我试图用
HomeActivity.mTitleTextView.setText("9999999999999999999999999999999999999999999999999999999999");
但错误的应用程序停机,我读过一些旧的文章和GOOGLE上搜索看到类似这样的广播接收器可以解决这个问题,但我并不真正了解它是如何工作的,任何人都可以证明它可以在我的情况可以应用于一些实际的源代码?
我们可以通过使用处理器,broadcat和侦听concept.But我认为广播是易于实现和理解,但需要照顾或注册和广播的注销实现。
使用LISTENER
创建一个监听器类
public Interface Listener{
public void onResultReceived(String str);
}
现在,实现它在活动像下面
public class MainActivity extends Activity implements listener{
public void onResultReceived(String str){
mTitleTextView.setText(str)
}
}
从OnCreate中活动的呼叫服务的构造函数初始化监听器
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
私人广播接收器mMessageReceiver =新的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)
使用处理,并从发送消息给父活动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);
内部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
这里是使用很好的例子。