Android Service 通过 BroadcastReceiver 更新Activity UI
1:MainActivity.java
public class MainActivity extends Activity { private TextView tvInfo = null; private BroadcastReceiver receiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvInfo = (TextView)findViewById(R.id.tvInfo); receiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { String info = intent.getExtras().getString("data"); tvInfo.setText(info); } }; IntentFilter filter = new IntentFilter(); filter.addAction("com.example.timejob.service"); registerReceiver(receiver,filter); } @Override protected void onResume() { super.onResume(); if(!isServiceRunning()){ Intent intent = new Intent(this,MyService.class); this.startService(intent); Log.d("onResume:", "服务运行"); } } @Override public void onStop() { super.onStop(); if(isServiceRunning()){ Intent is = new Intent(this,MyService.class); this.stopService(is); Log.d("onStop:", "服务关闭"); } this.unregisterReceiver(receiver); } /* * 判断service是否运行 */ private boolean isServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("com.example.timejob.MyService".equals(service.service.getClassName())) { return true; } } return false; } }
2:MyService.java
public class MyService extends Service{ public Timer timer = null; public String info = null; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { doJob(); return super.onStartCommand(intent, flags, startId); } private void doJob(){ timer = new Timer(); //10s触发一次 timer.schedule(new MyTimerWork(),0, 1000*10); } private class MyTimerWork extends TimerTask{ @Override public void run() { info = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); Intent intent = new Intent(); intent.setAction("com.example.timejob.service"); intent.putExtra("data", info); sendBroadcast(intent); Log.d("MyTimerWork:", "定时任务执行:"+info); } } @Override public void onDestroy() { super.onDestroy(); if(null!=timer){ timer.cancel(); } } }
3:AndroidManifest.xml
<service android:name="com.example.timejob.MyService" android:enabled="true" android:exported="false" />