Android Messenger IPC 通信

服务端通知客户端

 

客户端:

 
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
@Override
public 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)