方法一:
使用ASB模型
1.Activity启动Service
2.Service发送广播
3.在Activity上注册BroadcastReceiver接受广播
public class MainActivity extends Activity { TextView tv; MyReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.tv); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); receiver=new MyReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction("ISAAC_MYSERVICE");//注册 registerReceiver(receiver, filter);//注销 } public void start(View v){ Intent intent =new Intent(this,MyService.class); startService(intent); } public void stop(View v){ Intent intent =new Intent(this,MyService.class); stopService(intent); } public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action =intent.getAction(); if("ISAAC_MYSERVICE".equals(action)){ String time = intent.getStringExtra("time"); tv.setText(time); } } } }
public class MyService extends Service { /** * onCreate() * onStartCommand * onDestroy() */ Handler h=new Handler(); public MyService() { } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); Log.i("boom","onCreate()"); h.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub //发送广播,把getServiceTime()发送出去 Intent intent = new Intent("ISAAC_MYSERVICE");//别跟系统重名 intent.putExtra("time", getServiceTime()); sendBroadcast(intent); h.postDelayed(this, 1000);//每个1秒发一次 } },1000); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub Log.i("boom","onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); h.removeCallbacksAndMessages(null); Log.i("boom","onDestroy()"); } String getServiceTime(){ SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:SS"); return sdf.format(new Date()); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
时间: 2024-10-15 08:13:06