| | |
| | | import android.support.annotation.Nullable; |
| | | import android.util.Log; |
| | | |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | |
| | | /** |
| | | * MyApplication2 |
| | | * Created by lzw on 2019/6/5. 13:22:46 |
| | |
| | | public class RemoteService extends Service { |
| | | |
| | | private static final String TAG = "RemoteService"; |
| | | //服务是否销毁 |
| | | private AtomicBoolean mIsServiceDestroyed = new AtomicBoolean(false); |
| | | private RemoteCallbackList<IListenerInterface> mListenerList = new RemoteCallbackList(); |
| | | private IListenerInterface mListener; |
| | | private int msgId = 0; |
| | | private IRemoteInterface.Stub iRemoteInterface = new IRemoteInterface.Stub(){ |
| | | @Override |
| | | public void registListener(IListenerInterface i) throws RemoteException { |
| | |
| | | |
| | | @Override |
| | | public void add() throws RemoteException { |
| | | |
| | | Log.i(TAG,"客户端调用服务端方法"); |
| | | } |
| | | |
| | | |
| | |
| | | public void onCreate() { |
| | | super.onCreate(); |
| | | Log.i(TAG,"onCreate()"); |
| | | new Thread(new Worker()).start(); |
| | | } |
| | | |
| | | private class Worker implements Runnable{ |
| | | |
| | | @Override |
| | | public void run() { |
| | | while (!mIsServiceDestroyed.get()){ |
| | | try { |
| | | Thread.sleep(4*1000); |
| | | } catch (InterruptedException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | onMessageArrived(String.format("消息ID:%d,请注意查收",msgId++)); |
| | | } |
| | | |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void onDestroy() { |
| | | super.onDestroy(); |
| | | Log.i(TAG,"onDestroy"); |
| | | mIsServiceDestroyed.set(true); |
| | | } |
| | | |
| | | private void onMessageArrived(String json){ |
| | | int N = mListenerList.getRegisteredCallbackCount(); |
| | | for (int i = 0; i < N; i++) { |
| | | mListenerList.beginBroadcast(); |
| | | mListener = mListenerList.getBroadcastItem(i); |
| | | if (mListener != null){ |
| | | try { |
| | | mListener.onMessageArrived(json); |
| | | } catch (RemoteException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | mListenerList.finishBroadcast(); |
| | | } |
| | | } |
| | | } |