Chinaunix首页 | 论坛 | 博客
  • 博客访问: 463367
  • 博文数量: 153
  • 博客积分: 3010
  • 博客等级: 中校
  • 技术积分: 1724
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-08 11:55
文章分类

全部博文(153)

文章存档

2011年(1)

2010年(55)

2009年(88)

2008年(9)

我的朋友

分类: LINUX

2010-10-27 08:35:23


An Example:

Client:App or Activity

    public synchronized void startImServiceIfNeed() {
        if(!mServiceStarted) {
            if(Log.isLoggable(LOG_TAG, Log.DEBUG)) log("start ImService");

            Intent serviceIntent = new Intent();
            serviceIntent.setComponent(ImServiceConstants.IM_SERVICE_COMPONENT);
            mApplicationContext.startService(serviceIntent);
            mApplicationContext.bindService(serviceIntent, mImServiceConn, Context.BIND_AUTO_CREATE);
            mServiceStarted = true;

            mConnectionListener = new MyConnListener(new Handler());
        }
    }

    public synchronized void stopImServiceIfInactive() {
        boolean hasActiveConnection = true;
        synchronized (mConnections) {
            hasActiveConnection = !mConnections.isEmpty();
        }

        if (!hasActiveConnection && mServiceStarted) {
            if (Log.isLoggable(LOG_TAG, Log.DEBUG))
                log("stop ImService because there's no active connections");

            if(mImService != null) {
                mApplicationContext.unbindService(mImServiceConn);
                mImService = null;
            }  
            Intent intent = new Intent();
            intent.setComponent(ImServiceConstants.IM_SERVICE_COMPONENT);
            mApplicationContext.stopService(intent);
            mServiceStarted = false;
        }  
    }  

    private ServiceConnection mImServiceConn = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
                                                                                                     if(Log.isLoggable(LOG_TAG, Log.DEBUG))
                log("service connected");

            mImService = IRemoteImService.Stub.asInterface(service);
            fetchActiveConnections();

            synchronized (mQueue) {
                for (Message msg : mQueue) {
                    msg.sendToTarget();
                }
                mQueue.clear();
            }
            Message msg = Message.obtain(null, EVENT_SERVICE_CONNECTED);
            mBroadcaster.broadcast(msg);
        }

        public void onServiceDisconnected(ComponentName className) {
            if(Log.isLoggable(LOG_TAG, Log.DEBUG))
                log("service disconnected");

            mConnections.clear();
            mImService = null;
        }
    };


RemoteService:

public class RemoteImService extends Service {
    public RemoteImService() {
        mConnections = new Vector();
    }  

    @Override
    public void onCreate() {
        mServiceHandler = new ServiceHandler();
        mNetworkConnectivityListener = new NetworkConnectivityListener();
        mNetworkConnectivityListener.registerHandler(mServiceHandler, EVENT_NETWORK_STATE_CHANGED);
        mNetworkConnectivityListener.startListening(this);

        mSettingsMonitor = new SettingsMonitor();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
        registerReceiver(mSettingsMonitor, intentFilter);

        ConnectivityManager manager
            = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        setBackgroundData(manager.getBackgroundDataSetting());

        mPluginHelper = ImPluginHelper.getInstance(this);
        mPluginHelper.loadAvaiablePlugins();
        AndroidSystemService.getInstance().initialize(this);
    }

// 关于onCreate():
如果需要启动一线程的话, 可以在onCreate()中创建,如下:
  1.     public void onCreate() {  
  2.         super.onCreate();  
  3.         Log.d(TAG, "============>  onCreate");  
  4.   
  5.          new Thread(new Runnable() {  
  6.           
  7.          @Override  
  8.          public void run() {  
  9.           
  10.          while (!threadDisable) {  
  11.          try {  
  12.          Thread.sleep(1000);  
  13.          } catch (InterruptedException e) {  
  14.          }  
  15.          count++;  
  16.          Log.d(TAG, "Count is " + count);  
  17.          }  
  18.          }  
  19.          }).start();    // Thread.start()
  20.     } 




//---------

    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mNeedCheckAutoLogin = intent.getBooleanExtra(ImServiceConstants.EXTRA_CHECK_AUTO_LOGIN, false);

        Log.d(TAG, "ImService.onStart, checkAutoLogin=" + mNeedCheckAutoLogin);

        // Check and login accounts if network is ready, otherwise it's checked
        // when the network becomes available.
        if (mNeedCheckAutoLogin &&
                mNetworkConnectivityListener.getState() == State.CONNECTED) {
            mNeedCheckAutoLogin = false;
            autoLogin();
        }
    }

    @Override
    public void onDestroy() {
        Log.w(TAG, "ImService stopped.");
        for (ImConnectionAdapter conn : mConnections) {
            conn.logout();
        }

        AndroidSystemService.getInstance().shutdown();

        mNetworkConnectivityListener.unregisterHandler(mServiceHandler);
        mNetworkConnectivityListener.stopListening();
        mNetworkConnectivityListener = null;

        unregisterReceiver(mSettingsMonitor);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

.............
    private final IRemoteImService.Stub mBinder = new IRemoteImService.Stub() {

        public List getAllPlugins() {
            return new ArrayList(mPluginHelper.getPluginsInfo());
        }

        public void addConnectionCreatedListener(IConnectionCreationListener listener) {
            if (listener != null) {
                mRemoteListeners.register(listener);
            }
        }

        public void removeConnectionCreatedListener(IConnectionCreationListener listener) {
            if (listener != null) {
                mRemoteListeners.unregister(listener);
            }
        }

        public IImConnection createConnection(long providerId) {
            return RemoteImService.this.createConnection(providerId);
        }

        public List getActiveConnections() {
            ArrayList result = new ArrayList(mConnections.size());
            for(IImConnection conn : mConnections) {
                result.add(conn.asBinder());
            }
            return result;
        }

        public void dismissNotifications(long providerId) {
            mStatusBarNotifier.dismissNotifications(providerId);
        }

        public void dismissChatNotification(long providerId, String username) {
            mStatusBarNotifier.dismissChatNotification(providerId, username);
        }
    };

    private final class SettingsMonitor extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
                                                                                                      
            if (ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED.equals(action)) {
                ConnectivityManager manager =
                    (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                setBackgroundData(manager.getBackgroundDataSetting());
                handleBackgroundDataSettingChange();
            }
        }
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_SHOW_TOAST:
                    Toast.makeText(RemoteImService.this,
                            (CharSequence) msg.obj, msg.arg1).show();
                    break;

                case EVENT_NETWORK_STATE_CHANGED:
                    networkStateChanged();
                    break;

                default:
            }
        }
    }
}
                                             

IRemoteService Interface:

interface IRemoteImService {

    /**
     * Gets a list of all installed plug-ins. Each item is an ImPluginInfo.
     */ 
    List getAllPlugins();

    /**
     * Register a listener on the service so that the client can be notified when
     * there is a connection be created.
     */ 
    void addConnectionCreatedListener(IConnectionCreationListener listener);

    /**
     * Unregister the listener on the service so that the client doesn't ware of
     * the connection creation anymore.
     */ 
    void removeConnectionCreatedListener(IConnectionCreationListener listener);

    /**
     * Create a connection for the given provider.
     */ 
    IImConnection createConnection(long providerId);

    /**
     * Get all the active connections.
     */
    List getActiveConnections();

    /**
     * Dismiss all notifications for an IM provider.
     */
    void dismissNotifications(long providerId);

    /**
     * Dismiss notification for the specified chat.
     */
    void dismissChatNotification(long providerId, String username);
}

阅读(986) | 评论(0) | 转发(0) |
0

上一篇:More on Service

下一篇:Content PRovider

给主人留下些什么吧!~~