Android Service Messenger响应空对象引用?

时间:2015-12-20 14:21:55

标签: java android service response messenger

我通过在Service-IncomingHandler中调用msg.replyTo(rsp)来获取null对象引用错误。

public class MessengerService extends Service {
/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1;

/**
 * Handler of incoming messages from clients.
 */
class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_SAY_HELLO:
                Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                Message resp = Message.obtain(null,msg.what);
                Bundle bResp = new Bundle();
                bResp.putString("respData", "Uppercase");
                resp.setData(bResp);
                try {
                   msg.replyTo.send(resp);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

/**
 * Target we publish for clients to send messages to IncomingHandler.
 */
final Messenger mMessenger = new Messenger(new IncomingHandler());

/**
 * When binding to the service, we return an interface to our messenger
 * for sending messages to the service.
 */
@Override
public IBinder onBind(Intent intent) {
    Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
    return mMessenger.getBinder();
   }
}

服务正在运行,我可以将消息发送到我的服务。

我的主要活动如下(应该可以正常工作):

public class MainActivity extends Activity {
/** Messenger for communicating with the service. */
Messenger mService = null;

/** Flag indicating whether we have called bind on the service. */
boolean mBound;

/**
 * Class for interacting with the main interface of the service.
 */
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the object we can use to
        // interact with the service.  We are communicating with the
        // service using a Messenger, so here we get a client-side
        // representation of that from the raw IBinder object.
        mService = new Messenger(service);
        mBound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mService = null;
        mBound = false;
    }
};

public void sayHello(View v) {
    if (!mBound) return;
    // Create and send a message to the service, using a supported 'what' value
    Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
    try {
        mService.send(msg);
        Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();

    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
private class ResponseHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        Toast.makeText(getApplicationContext(), "message from service",Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Messenger messenger = new Messenger(new ResponseHandler());

}

@Override
protected void onStart() {
    super.onStart();
    // Bind to the service
    bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
 }

}

这是我的清单(我认为这个清单已经很好了):

<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="app.test.mservs.fronservicesetc">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MessengerService" >
    </service>
</application>  

目标是将我的服务响应发送到我的MainActivity。

1 个答案:

答案 0 :(得分:0)

sayHello中调用onServiceConnected方法,并将null传递给参数。