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()中创建,如下:
- public void onCreate() {
- super.onCreate();
- Log.d(TAG, "============> onCreate");
-
- new Thread(new Runnable() {
-
- @Override
- public void run() {
-
- while (!threadDisable) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- count++;
- Log.d(TAG, "Count is " + count);
- }
- }
- }).start(); // Thread.start()
- }
//---------
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);
}
阅读(1019) | 评论(0) | 转发(0) |