1
我有一個服務在後臺運行,從一個活動開始,沒有活動就開始工作。使用ResultReceiver,我可以與活動進行通信,但只要活動處於活動狀態即可。一旦下降並重新開始,就沒有任何通信返回到活動。我錯了什麼?ResultReceiver從服務到活動
// Activity
public void onReceiveResult(int resultCode, Bundle resultData) {
String test = resultData.getString("Event");
}
public MyResultReceiver mReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
Intent i=new Intent(this, AppService.class);
i.putExtra(AppService.TIME, spinner_time.getSelectedItemPosition());
startService(i);
// Service
public class AppService extends Service {
public static final String TIME="TIME";
int time_loud;
Notification note;
Intent i;
private boolean flag_silencemode = false;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
time_loud = intent.getIntExtra(TIME, 0);
resultReceiver = intent.getParcelableExtra(RESULT_RECEIVER);
resultData = new Bundle();
resultData.putString("Event", "ysfgsdfgsdfg");
resultReceiver.send(55, resultData);
play(time_loud);
return(START_NOT_STICKY);
}
@SuppressLint("ParcelCreator")
public class MyResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
void onReceiveResult(int resultCode, Bundle resultData);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
非常感謝它的工作。我像這樣實現它:http://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager – user1390816