我有一个启动服务的Activity。我希望该服务能够访问Activity的成员变量之一(布尔值)。我在Activity中实现了一个getBoolean()方法,但是如何在服务中实例化Activity以使其访问?
答案 0 :(得分:0)
你没有。相反,请使用广播接收器或共享偏好。
使用广播接收器的示例 -
public class MyService extends Service {
boolean mActivityBoolean;
BooleanReceiver mReceiver;
@Override
public void onCreate() {
super.onCreate();
mReceiver = new BooleanReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(
mReceiver, new IntentFilter("activityBooleanIntent")
);
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
super.onDestroy();
}
public class BooleanReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
mActivityBoolean = intent.getBooleanExtra("activityBoolean", false);
}
}
}
public class MyActivity extends Activity {
void someMethodThatSendsABooloean(boolean trueOrFalse) {
.....
Intent intent = new Intent();
intent.setAction("activityBooleanIntent");
intent.putExtra("activityBoolean", trueOrFalse);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
答案 1 :(得分:0)
使用SharedPreferences在活动中保存数据,yu可以在服务中访问它 在启动服务时的OnStartCommand方法
SharedPreferences sharedPref = getSharedPreferences(“MYPREF”,Context.MODE_PRIVATE); sharedPref.getBoolean( “标志”,假);