Android(安卓)Messenger IPC 通信
16lz
2021-12-04
服务端通知客户端
客户端:
MainActivity.java
protected void onStart() { super.onStart(); // Start service and provide it a way to communicate with this class. Intent startServiceIntent = new Intent(this, MyJobService.class); Messenger messengerIncoming = new Messenger(mHandler); startServiceIntent.putExtra(MESSENGER_INTENT_KEY, messengerIncoming); startService(startServiceIntent);}
服务端
MyJobService.java
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) { mActivityMessenger = intent.getParcelableExtra(MESSENGER_INTENT_KEY); return START_NOT_STICKY;}
long duration = params.getExtras().getLong(WORK_DURATION_KEY);// Uses a handler to delay the execution of jobFinished().Handler handler = new Handler();handler.postDelayed(new Runnable() { @Override public void run() { sendMessage(MSG_COLOR_STOP, params.getJobId()); jobFinished(params, false); }}, duration);Log.i(TAG,
private void sendMessage(int messageID, @Nullable Object params) { // If this service is launched by the JobScheduler, there's no callback Messenger. It // only exists when the MainActivity calls startService() with the callback in the Intent. if (mActivityMessenger == null) { Log.d(TAG, "Service is bound, not started. There's no callback to send a message to."); return; } Message m = Message.obtain(); m.what = messageID; m.obj = params; try { mActivityMessenger.send(m); } catch (RemoteException e) { Log.e(TAG, "Error passing service object back to activity."); }}
更多相关文章
- android javamail客户端获取慢_Android面经分享,失业两个月,五一节
- android之【本地通知Notification】
- Android(安卓)通知栏Notification 悬浮通知栏
- Android(安卓)网页加载完成ProgressDialog运用
- Android(安卓)8.0新特性调研
- Android状态栏通知
- android通知栏提示
- Android与服务器通信的方法之一-->TCP
- Android(安卓)(Notification)消息推送机制