从 IntentService 向 Activity 发送数据
关键词是BroadcastReceiver
BroadcastReceiver 在这种情况下很方便。
- 从 IntentService 发送广播
- 在 Activity 中接收广播。
从服务发送数据
public class YourService extends IntentService {
public YourService() {
super("yourService");
}
protected void onHandleIntent(@Nullable Intent intent) {
sendDataToActivity()
}
private void sendDataToActivity()
{
Intent sendLevel = new Intent();
sendLevel.setAction("TIMER_ACTION");
sendLevel.putExtra( "TIMER_VALUE","This is the value from service");
sendBroadcast(sendLevel);
}
}
从服务接收数据
为此,您需要注册您Activity
的BroadcastReceiver
public class YourActivity extends AppCompatActivity {
TimerReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.track_wifi_activity_layout);
receiver = new TimerReceiver();
registerReceiver(receiver, new IntentFilter("TIMER_ACTION")); //<----Register
}
@Override
public void onStop()
{
super.onStop();
unregisterReceiver(receiver); //<-- Unregister to avoid memoryleak
}
class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("TIMER_ACTION"))
{
int level = intent.getStringExtra("TIMER_VALUE");
// Show it in activity
}
}
}
}