Service(二)

Mainfest代码清单:

<serviceandroid:enabled="true"android:label="DummyService"android:name=".DummyService">

        <intent-filter>

        <actionandroid:name="org.demo.DummyService"/>

        </intent-filter>

一、使用Service和Broadcast更新UI界面

Service类:

public class ServiceUIService extends Service{

 

        public static final String SERVICEUI_SERVICE = "com.cmd100.serviceui";

        

        @Override

        public IBinder onBind(Intent intent) {

                // TODO Auto-generated method stub

                return null;

        }

        

        @Override

        public void onCreate() {

                //发送0显示ProcessDialog

                updateProgressDialogValue(0);

                //在新线程里处理业务,防止影响主线程界面显示,测试时发现如果通过handler来处理会导致ProcessDialog界面假死

                thread.start();                

                super.onCreate();

        }

 

        private void updateProgressDialogValue(int value){

             //利用service发送广播

                Intent i = new Intent(SERVICEUI_SERVICE);

                Bundle b = new Bundle();

                b.putInt("ProgressDialogValue", value);

                b.putString("data", "此程序应该可以符合你要求了,其实关键点就是在services里要新开线程去处理业务和广播发送即可。如果不开新线程的话,的确会影响主Activity的界面显示。其实不用广播也可以达到要求,我做的程序里也要通过service的执行情况,去更新启动它的activity,我用了全局对象,service会对全局对象里的变量进行更新,然后activity里使用handler查看全局对象中变量的状态,然后再来更新UI");

                i.putExtras(b);

                sendBroadcast(i);

        }

        

        private Runnable doYourWorkInService = new Runnable() {                        

              public void run() {

                                //模拟一段时间的数据处理操作

                                long count =0;

                do {

                        count ++;

                } while (count<3000);

                try {

                  Thread.sleep(5000);

              } catch (InterruptedException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

                //业务操作完成后再发广播

                updateProgressDialogValue(100);

                }

                };

                

        Thread thread = new Thread(doYourWorkInService);

}

posted @ 2011-08-29 23:04  rorshach  阅读(126)  评论(0编辑  收藏  举报