service代码
package com.example.ketang1022serverclient;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.ketang1022serverclient;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
public class MyService extends Service {
public MyService() {
}
Messenger messenger = new Messenger(new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
Bundle data = msg.getData();
String sss = data.getString("sss");
Log.i("TAG", "handleMessage: "+sss);
super.handleMessage(msg);
}
});
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
}
client代码
package com.example.app2;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
public class MainActivity extends AppCompatActivity {
private Messenger messenger;
private ServiceConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection =new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messenger = new Messenger(iBinder);
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("sss","Android Studio ???????");
message.setData(bundle);
message.replyTo = messenger;
try {
messenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
Intent intent = new Intent();
intent.setPackage("com.example.ketang1022serverclient");
intent.setAction("com.w.w");
startService(intent);
bindService(intent, connection, Service.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}