在基于服务的类中设置一个监听器监听器、类中

2023-09-05 05:18:13 作者:★亂る分寸の心動·

海兰我有一个问题,设置ServiceUpdateUIListener在服务更新UI。这是错误的,使一个新的服务对象,并设置有听众,并把它放在一个意图。

code源代码是 http://developerlife.com/tutorials/?p=356 在那里,我怎么也找不到了设置监听器和启动服务的权利。

电话:

  TimerService服务=新TimerService();
                TimerService.setUpdateListener(新ServiceUpdateUIListener(){

                    @覆盖
                    方法public void updateUI(字符串时){
                        clock.setText(时间);

                    }
                });

                意图I =新的意图(Timer.this,service.class); //服务不能被解析为一个类型
                i.putExtra(毫秒,毫秒);
                startService(ⅰ);
 

服务:

 公共类TimerService延伸服务{

        CountDownTimer定时器;
        记时计时钟;
        公共静态ServiceUpdateUIListener UI_UPDATE_LISTENER;

        @覆盖
        公众的IBinder onBind(意向意图){

            返回null;
        }
        @覆盖
        公共无效ONSTART(意向意图,诠释startId){
            // TODO自动生成方法存根
            诠释毫秒= intent.getIntExtra(毫秒,0);

            定时器=新CountDownTimer(MS,1000){
                @覆盖
                公共无效onTick(长millisUntilFinished){

                    INT秒=(INT)(millisUntilFinished / 1000)%60;
                    INT分钟=(int)的((millisUntilFinished /(1000 * 60))%60);
                    INT小时=(INT)((millisUntilFinished /(1000 * 60 * 60))%24);

                    clock.setText(的String.Format(%02D:%02D:%02D,时,分,秒));
                    Log.e(定时器,将String.valueOf(millisUntilFinished));

                }

                @覆盖
                公共无效onFinish(){
                    // TODO自动生成方法存根

                }
            }。开始();
            super.onStart(意向,startId);
        }
        公共静态无效setUpdateListener(ServiceUpdateUIListener L){
             UI_UPDATE_LISTENER =升;

        }
 
Java当中Listener Filter的作用和用法,监听三个作用域创建和销毁,监听三个作用域属性状态变更,监听httpSession里面存值的状态变更

解决方案

在服务文档中有相当完整的示例code实现你的应用程序中的服务,您的应用程序的另一部分可以结合并拨打电话:

http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

只要把你的setUpdateListener()方法,在服务上,并调用它,一旦你得到onServiceConnected()的服务。

所以,你的code将是这样的:

 公共接口UpdateListener {
    公共无效的OnUpdate(long值);
}

一流的本地服务{
    //就像在服务样本code,外加:

    公共静态字符串ACTION_START =com.mypackage.START;

    私人最终的ArrayList< UpdateListener> mListeners
            =新的ArrayList< UpdateListener>();
    私人最终处理程序mHandler =新的处理程序();

    私人长mTick = 0;

    私人最终可运行mTickRunnable =新的Runnable(){
        公共无效的run(){
            mTick ++;
            sendUpdate(mTick);
            mHandler.postDelayed(mTickRunnable,1000);
        }
    }

    公共无效registerListener(UpdateListener监听器){
        mListeners.add(听众);
    }

    公共无效unregisterListener(UpdateListener监听器){
        mListeners.remove(听众);
    }

    私人无效sendUpdate(long值){
        的for(int i = mListeners.size() -  1; I> = 0;我 - ){
            mListeners.get(我).onUpdate(值);
        }
    }

    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        如果(ACTION_START.equals(intent.getAction()){
            mTick = 0;
            mHandler.removeCallbacks(mTickRunnable);
            mHandler.post(mTickRunnable);
        }
        返回START_STICKY;
    }

    公共无效的onDestroy(){
        mHandler.removeCallbacks(mTickRunnable);
    }
 

现在,你可以启动该服务得到它开始计数,任何人都可以绑定到它注册一个监听器来接收回调,因为它计数。

这是真的很难,虽然回答你的问题非常好,因为你并没有真正说了什么,你真正想要完成的任务。有很多方法可以使用​​的服务,无论是启动或结合或两者混合在一起,这取决于你想完成什么。

现在,你可以实现你的客户端code再根据样本:

 公共类SomeActivity扩展活动实现UpdateListener {
    私人本地服务mBoundService;

    私人ServiceConnection mConnection =新ServiceConnection(){
        公共无效onServiceConnected(组件名的className,服务的IBinder){
            mBoundService =((LocalService.LocalBinder)服务).getService();
            mBoundService.registerListener(本);
        }

        公共无效onServiceDisconnected(组件名的className){
            mBoundService = NULL;
        }
    };

    无效doBindService(){
        bindService(新意图(Binding.this,
                LocalService.class),mConnection,Context.BIND_AUTO_CREATE);
        mIsBound = TRUE;
    }

    无效doUnbindService(){
        如果(mIsBound){
            如果(mBoundService!= NULL){
                mBoundService.unregisterListener(本);
            }
            unbindService(mConnection);
            mIsBound = FALSE;
        }
    }

    保护无效的onDestroy(){
        super.onDestroy();
        doUnbindService();
    }
 

Hy i have a problem to set the ServiceUpdateUIListener in the service to update the UI. It's wrong to make a new Service object and set there the listener and put it in an intent.

Code source is at http://developerlife.com/tutorials/?p=356 there i can't find how the set the listener and start the service right.

Calling:

TimerService service = new TimerService();
                TimerService.setUpdateListener(new ServiceUpdateUIListener() {

                    @Override
                    public void updateUI(String time) {
                        clock.setText(time);

                    }
                });

                Intent i  = new Intent(Timer.this,service.class); //service cannot be resolved to a type
                i.putExtra("ms", ms);
                startService(i);  

Service:

 public class TimerService extends Service{

        CountDownTimer timer;
        Chronometer clock;
        public static ServiceUpdateUIListener UI_UPDATE_LISTENER;

        @Override
        public IBinder onBind(Intent intent) {

            return null;
        }
        @Override
        public void onStart(Intent intent, int startId) {
            // TODO Auto-generated method stub
            int ms = intent.getIntExtra("ms", 0);

            timer = new  CountDownTimer(ms,1000){
                @Override
                public void onTick(long millisUntilFinished) {

                    int seconds = (int) (millisUntilFinished / 1000) % 60 ;
                    int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
                    int hours   = (int) ((millisUntilFinished / (1000*60*60)) % 24);

                    clock.setText( String.format("%02d:%02d:%02d", hours,minutes,seconds));
                    Log.e("Timer", String.valueOf(millisUntilFinished));

                }

                @Override
                public void onFinish() {
                    // TODO Auto-generated method stub

                }
            }.start();
            super.onStart(intent, startId);
        }
        public static void setUpdateListener(ServiceUpdateUIListener l) {
             UI_UPDATE_LISTENER = l;

        }

解决方案

The Service documentation has fairly complete sample code for implementing a service in your app that another part of your app can bind to and make calls on:

http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

Just put your setUpdateListener() method on the Service, and call it once you get onServiceConnected() with the service.

So your code would be something like this:

public interface UpdateListener {
    public void onUpdate(long value);
}

class LocalService {
    // Like in the Service sample code, plus:

    public static String ACTION_START = "com.mypackage.START";

    private final ArrayList<UpdateListener> mListeners
            = new ArrayList<UpdateListener>();
    private final Handler mHandler = new Handler();

    private long mTick = 0;

    private final Runnable mTickRunnable = new Runnable() {
        public void run() {
            mTick++;
            sendUpdate(mTick);
            mHandler.postDelayed(mTickRunnable, 1000);
        }
    }

    public void registerListener(UpdateListener listener) {
        mListeners.add(listener);
    }

    public void unregisterListener(UpdateListener listener) {
        mListeners.remove(listener);
    }

    private void sendUpdate(long value) {
        for (int i=mListeners.size()-1; i>=0; i--) {
            mListeners.get(i).onUpdate(value);
        }
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        if (ACTION_START.equals(intent.getAction()) {
            mTick = 0;
            mHandler.removeCallbacks(mTickRunnable);
            mHandler.post(mTickRunnable);
        }
        return START_STICKY;
    }

    public void onDestroy() {
        mHandler.removeCallbacks(mTickRunnable);
    }

Now you can start the service to get it to start counting, and anyone can bind to it to register a listener to receive callbacks as it counts.

It is really hard though to answer your question very well because you aren't really saying what you actually want to accomplish. There are a lot of ways to use services, either starting or binding or mixing the two together, depending on exactly what you want to accomplish.

Now you can implement your client code again based on the sample:

public class SomeActivity extends Activity implements UpdateListener {
    private LocalService mBoundService;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((LocalService.LocalBinder)service).getService();
            mBoundService.registerListener(this);
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    void doBindService() {
        bindService(new Intent(Binding.this, 
                LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {
            if (mBoundService != null) {
                mBoundService.unregisterListener(this);
            }
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }