我有一个可以接收 gcm 推送通知的应用程序。我还进行了检查,如果应用程序当前打开,则不会创建通知。在Android中,我的推送服务是否可以告诉当前 Activity (如果可用/已连接),新通知已到达,用新内容刷新您的列表?如果这是可能的,我相信我在我的服务中使用 IBinders 的道路是正确的。问题是我对服务如何调用 Activity 感到困惑(我理解反之亦然)。如果有人可以提供帮助,请提前致谢!
只是为了清楚起见。我正在尝试告诉 Activity 有一条新的推送消息。
服务
public class LocalBinder extends Binder {
GcmIntentService getService() {
return GcmIntentService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
客户端( Activity )
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((GcmIntentService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
Toast.makeText(MainActivity.this, "Disconnected",
Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(MainActivity.this,
GcmIntentService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
最佳答案
是的,这是可能的。
在您的服务类中有一个 YourActivity 类型的变量
MyActivity myActivity = null;
在您的 onServiceConnected
方法中,在服务上设置通过绑定(bind)器获取的 myActivity 变量。
mBoundService.myActivity = MyActivity.this; // or something similar
现在你的服务有一个指向你的 Activity 的指针!!!是啊!!
在您的 Activity 中,创建一个函数,该函数的主体应使用数据刷新 UI。
最后,当服务检测到新数据时,调用:
if (myActivity)
myActivity.refreshMyData();
解绑时,记得将myActivity变量设置为null,否则前面的代码会失败。
关于java - Android通过Local Service向Activity发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21966026/