实现逻辑如下:
左侧为Activity中的执行逻辑,右侧为Service中的执行逻辑:
/**
* <功能描述> Service和Activity之间的数据交互;具体表现为: 1. 从Service获取数据源,传递到Activity中; 2.
* 在Activity中作数据更新; 3. Service中的onCreate()在UI线程中执行,作延时需要在子线程中执行;
*
* @author Administrator
*/
public class MainActivity extends Activity {
private static final String TAG = "Demo";
private TextView mTvContent;
private Intent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
registerReceiver();
initData();
}
/**
* <功能描述> 初始化视图
*
* @return void [返回类型说明]
*/
private void initView() {
setContentView(R.layout.activity_main);
mTvContent = (TextView) findViewById(R.id.tv_data);
}
/**
* <功能描述> 初始化数据
*
* @return void [返回类型说明]
*/
private void initData() {
mIntent = new Intent(MainActivity.this, CountService.class);
startService(mIntent);
}
/**
* <功能描述> 注册广播
*
* @return void [返回类型说明]
*/
private void registerReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.spt.activity.CountService");
MainActivity.this.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
mTvContent.setText(bundle
.getInt("com.spt.CountService.count_data") + "");
Log.d(TAG, "count_data=" + mTvContent.getText());
}
}, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (true) {
stopService(mIntent);
}
}
}
需要在MainActivity中注册能够接收Service发送的数据更新广播:com.spt.activity.CountService;并获取到更新后的数据,显示即可。
还需要注意的是:开启服务后,还要停止服务。否则该服务会一直在后台运行。
还发现,使用这种方式同样能够停止该Service:
stopService(new Intent(MainActivity.this, CountService.class));
CountService服务代码如下:
public class CountService extends Service {
private int countService = 0;
private boolean isServiceRunning = false;
@Override
public void onCreate() {
super.onCreate();
isServiceRunning = true;
// 创建子线程作计数
new Thread(new Runnable() {
@Override
public void run() {
while (isServiceRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countService++;
Intent intent = new Intent();
intent.putExtra("com.spt.CountService.count_data", countService);
intent.setAction("com.spt.activity.CountService");
// Service中发送广播
sendBroadcast(intent);
}
}
}).start();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
countService = 0;
}
}
总结和疑问:
1. 使用Broadcast广播方式实现服务和宿主之间的数据交互,容易造成性能不高的问题;
2. 广播发送的时间不确定性因素,导致数据交互有延时;