Android 将事件从非活动类传递到活动类
我有一个用于布局的活动类A和一个用于位置请求的非活动类B;类B触发了一些事件,如onConnectionSuspended,我想将这些事件返回到类A中。我该怎么做?Android 将事件从非活动类传递到活动类,android,android-studio,events,Android,Android Studio,Events,我有一个用于布局的活动类A和一个用于位置请求的非活动类B;类B触发了一些事件,如onConnectionSuspended,我想将这些事件返回到类A中。我该怎么做? 谢谢你之前的回答,我已经做了,但我补充了一些细节 我想将活动代码与GoogleApi.Connection代码分开。为此,我制作了一个带有连接代码的非活动类(也许服务更好?)(请参见下面的结构代码) 1) 这是个好主意吗? 2) 如果不是,那么最好做什么(可能把所有人都放在同一个活动中? 3) 如果是,我不认为我可以在非活动代码的c
谢谢你之前的回答,我已经做了,但我补充了一些细节 我想将活动代码与GoogleApi.Connection代码分开。为此,我制作了一个带有连接代码的非活动类(也许服务更好?)(请参见下面的结构代码) 1) 这是个好主意吗?
2) 如果不是,那么最好做什么(可能把所有人都放在同一个活动中?
3) 如果是,我不认为我可以在非活动代码的connections事件中添加一些“Toast”,那么如何在活动中获取connections事件以显示一些消息?
谢谢你的回答
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
public class SATlocation implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
在活动中使用本地广播接收器添加接收器,如下所示
private BroadcastReceiver onNotice = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// intent can contain anydata
}
}
内部onresume寄存器接收器,如下所示
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, intentFilter);
}
在onPause中注销接收器
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
在您的位置服务中添加以下代码以发送本地广播
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
作为广播接收器的替代方案,如果您可以从活动访问class B实例,还可以创建一个用于侦听这些事件的接口
public interface LocationRequestEventListener {
void onConnectionSuspended();
...
}
public class SomeActivity extends Activity implements LocationRequestEventListener {
private ClassB classB;
@Override
public void onCreate() {
...
classB.setListener(this);
}
...
@Override
void onConnectionSuspended() {
//react to the event here
}
}
public class ClassB {
private LocationRequestListener listener;
....
public void setListener(LocationRequestListener listener) {
this.listener = listener;
}
private void connectionSuspended() {
// suppose this is where your class fire the event of interest
if (listener != null) {
listener.onConnectionSuspended();
}
}
}