Android Activity通过Service更新时间
来源:互联网 发布:百科门窗软件下载 编辑:程序博客网 时间:2024/06/01 14:46
Android中Service功能强大,使用它来更新时间简直是大材小用,然而作为我们学习练习,这样使用也是情有可原的,通过这样简单的使用,来熟悉Service的基本用法,通俗易懂,还是比较容易理解的
启动Service有两种方式,分别是调用startService()和bindService()来启动,我们就分别使用这两种方式来更新界面时间
基本知识:
一、startService()和bindService()启动Service的区别,从Service启动的生命周期来看,区别还是比较大的
二、Service与Activity的通信方式,在这里我们使用接口和广播,实现如下:
接口:
public interface InTimeListener { public void callBackFun(Bundle bundle);}
TimeService:
public class TimeService extends Service { private boolean serviceRunning = false; private InTimeListener inTimerListener; public class TimeBinder extends Binder { TimeService getService() { return TimeService.this; } } public void onCreate() { super.onCreate(); System.out.println("--TimeService onCreate()--"); serviceRunning = true; } public void beginTimeListener() { new Thread() { public void run() { while (serviceRunning) { Bundle timeBundle = getTime(); /** 使用广播传递信息 */ Intent intent = new Intent(); intent.setAction("com.example.administrator.javastudy.service.TimeReceiver"); intent.putExtras(timeBundle); sendBroadcast(intent); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } public void startTimeListener() { if (inTimerListener != null) { new Thread() { public void run() { while (serviceRunning) { Bundle timeBundle = getTime(); /** 使用回调函数传递信息 */ inTimerListener.callBackFun(timeBundle); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } } public Bundle getTime() { Calendar calendar = Calendar.getInstance(); Bundle timeBundle = new Bundle(); timeBundle.putString("year", String.valueOf(calendar.get(Calendar.YEAR))); timeBundle.putString("month", String.valueOf(calendar.get(Calendar.MONTH) + 1)); timeBundle.putString("day", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))); timeBundle.putString("hour", String.valueOf(calendar.get(Calendar.HOUR_OF_DAY))); timeBundle.putString("minute", String.valueOf(calendar.get(Calendar.MINUTE))); timeBundle.putString("second", String.valueOf(calendar.get(Calendar.SECOND))); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strFormattTme = format.format(new Date(System.currentTimeMillis())); timeBundle.putString("formatTime", strFormattTme); return timeBundle; } /** 设置回调接口 **/ public void setTimerLintener(InTimeListener inTimerListener) { this.inTimerListener = inTimerListener; } public IBinder onBind(Intent intent) { // bindService()方式启动时调用 System.out.println("--TimeService onBind()--"); return new TimeBinder(); } public int onStartCommand(Intent intent, int flags, int startId) { // 使用startService()方式启动时调用 beginTimeListener(); System.out.println("--TimeService onStartCommand()--"); return super.onStartCommand(intent, flags, startId); } public boolean onUnbind(Intent intent) { System.out.println("--TimeService onUnbind()--"); return super.onUnbind(intent); } public void onDestroy() { serviceRunning = false; System.out.println("--TimeService onDestroy()--"); super.onDestroy(); }}
广播接收者:
public class TimeReceiver extends BroadcastReceiver { private InTimeListener inTimeListener; public void onReceive(Context context, Intent intent) { if(inTimeListener!= null){ Bundle dataBundle = intent.getExtras(); inTimeListener.callBackFun(dataBundle); } } public void setmTimeListener(InTimeListener inTimeListener){ this.inTimeListener = inTimeListener; }}
TimeActivity:
public class TimeActivity extends AppCompatActivity { private TextView mTxtTime; private Intent mIntent; private TimeService mTimeService; private TimeServiceConn mTimeServiceConn; private TimeService.TimeBinder mTimeBinder = null; private TimeReceiver mTimeReceiver; /** * Handler处理信息 */ private Handler mHandler = new Handler() { public void handleMessage(Message msg) { //在handler中更新UI Bundle timeBundle = msg.getData(); String strYear = timeBundle.getString("year") + "年 " + timeBundle.getString("month") + "月 " + timeBundle.getString("day") + "日 " + timeBundle.getString("hour") + "时 " + timeBundle.getString("minute") + "分 " + timeBundle.getString("second") + "秒"; mTxtTime.setText(strYear); } }; /** * 广播接收器接收信息(静态注册方式) * TimeActivity$TimeReceiver; no empty constructor * http://blog.csdn.net/xzongyuan/article/details/39991509 */// public class TimeReceiver extends BroadcastReceiver {// public void onReceive(Context context, Intent intent) {// Bundle timeBundle = intent.getExtras();// String strYear = timeBundle.getString("year") +// "年 " + timeBundle.getString("month") +// "月 " + timeBundle.getString("day") +// "日 " + timeBundle.getString("hour") +// "时 " + timeBundle.getString("minute") +// "分 " + timeBundle.getString("second") +// "秒";// mTxtTime.setText(strYear);// }// } class TimeServiceConn implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("---ServiceConnection onServiceConnected()---"); mTimeBinder = (TimeService.TimeBinder) service; mTimeService = mTimeBinder.getService(); mTimeBinder.getService().setTimerLintener( new InTimeListener() { @Override public void callBackFun(Bundle bundle) { Message msg = new Message(); msg.setData(bundle); mHandler.sendMessage(msg); } }); } public void onServiceDisconnected(ComponentName name) { System.out.println("---ServiceConnection onServiceDisconnected()---"); mTimeBinder = null; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("---MainActivity onCreate()---"); setContentView(R.layout.activity_time); onInit(); } public void onInit() { mTxtTime = (TextView) findViewById(R.id.txt_time); mIntent = new Intent(this, TimeService.class); mTimeServiceConn = new TimeServiceConn(); /** * 启动Service方式一:startService * */ startService(mIntent); /** * 启动Service方式二:bindService * */// bindService(mIntent, mTimeServiceConn, Context.BIND_AUTO_CREATE); /** * 动态广播注册 * */ mTimeReceiver = new TimeReceiver(); mTimeReceiver.setmTimeListener(new InTimeListener() { // 回调函数 public void callBackFun(Bundle timeBundle) { if (timeBundle != null) { String strYear = timeBundle.getString("year") + "年 " + timeBundle.getString("month") + "月 " + timeBundle.getString("day") + "日 " + timeBundle.getString("hour") + "时 " + timeBundle.getString("minute") + "分 " + timeBundle.getString("second") + "秒"; String strFormatTime = timeBundle.getString("formatTime"); mTxtTime.setText(strFormatTime); } } }); IntentFilter filter = new IntentFilter(); filter.addAction("com.example.administrator.javastudy.service.TimeReceiver"); registerReceiver(mTimeReceiver,filter); } public void onStart() { super.onStart(); System.out.println("---MainActivity onStart()---"); } public void onResume() { super.onResume(); System.out.println("---MainActivity onResume()---"); if (mTimeService != null) { mTimeService.startTimeListener(); } } public void onPause() { super.onPause(); System.out.println("---MainActivity onPause()---"); } public void onStop() { super.onStop(); System.out.println("---MainActivity onStop()---"); } public void onDestroy() { /** * 停止service方式一:stopService * */ stopService(mIntent); /** * 停止service方式二:unbindService * */// if (mTimeBinder != null) {// unbindService(mTimeServiceConn);// } unregisterReceiver(mTimeReceiver); System.out.println("---MainActivity onDestroy()---"); super.onDestroy(); }
Service注册:
<!-- 注册service --> <service android:name="com.example.administrator.javastudy.service.TimeService" /> </application>
结果截图:
0 0
- Android Activity通过Service更新时间
- Android Service 通知Activity更新界面的方法研究|Service通过Broadcast更新UI
- Android Service 通知Activity更新界面的方法研究|Service通过Broadcast更新UI
- Android Service 通知Activity更新界面的方法研究|Service通过Broadcast更新UI
- Service通过广播Broadcast更新Activity UI
- Service通过广播Broadcast更新Activity UI
- Service通过广播Broadcast更新Activity UI
- Service通过广播Broadcast更新Activity UI
- 【Android】关于在Service中通过接口回调更新Activity的UI
- Android 在service 更新activity UI
- Android:Service通知Activity更新界面
- android activity和service通过contentprovider通信
- Android Service通过Handler与Activity交互
- 【Android】Service通过广播更新UI
- 【Android】Service通过广播更新UI
- 后台Service通过广播更新UI,Activity通过广播停止Service
- Android Service 通知Activity更新界面的方法研究
- Android Service 通知Activity更新界面的方法研究
- SVN删除更新小技能
- LWIP之opt.h配置含义
- Android 系统使用USB OTG功能/打开USB Host API功能
- android支持https通讯,交叉编译 libcurl libnghttp2 oponssl
- JS判断移动设备 并跳转至手机版网页
- Android Activity通过Service更新时间
- 推荐一个 ARM Cortex-M 错误追踪库
- SetWindowsHookEx设置全局钩子
- 使用maven profile实现多环境可移植构建
- 【Codeforces 776 C. Molly's Chemicals】+ map + 前缀和
- 模板_poj2299Ultra-QuickSort_归并排序qiu
- Android 登录输入框自动上移
- 关于jQuery的Ajax操作
- MyEclipse安装JS代码提示插件——Spket插件)