Messenger
ServerService
public class ServerService extends Service {
public ServerService ( ) {
}
Messenger messenger= new Messenger ( new Handler ( ) {
@Override
public void handleMessage ( Message msg) {
super . handleMessage ( msg) ;
Bundle data = msg. getData ( ) ;
String key = data. getString ( "key" ) ;
Toast. makeText ( ServerService. this , key, Toast. LENGTH_SHORT) . show ( ) ;
Messenger to = msg. replyTo;
Message obtain = Message. obtain ( ) ;
Bundle bundle = new Bundle ( ) ;
bundle. putString ( "ser" , "hahaha" ) ;
obtain. setData ( bundle) ;
try {
to. send ( obtain) ;
Log. i ( "TAG" , obtain+ "" ) ;
} catch ( RemoteException e) {
e. printStackTrace ( ) ;
}
}
} ) ;
@Override
public IBinder onBind ( Intent intent) {
return messenger. getBinder ( ) ;
}
}
client
public class MainActivity extends AppCompatActivity {
private ServiceConnection connection;
private Messenger mes= new Messenger ( new Handler ( ) {
@Override
public void handleMessage ( Message msg) {
super . handleMessage ( msg) ;
Bundle data = msg. getData ( ) ;
String s = data. getString ( "ser" ) ;
Log. i ( "TAG" , s) ;
Toast. makeText ( MainActivity. this , s, Toast. LENGTH_SHORT) . show ( ) ;
}
} ) ;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R. layout. activity_main) ;
Intent intent = new Intent ( ) ;
intent. setPackage ( "com.example.day16" ) ;
intent. setAction ( "server" ) ;
connection = new ServiceConnection ( ) {
@Override
public void onServiceConnected ( ComponentName name, IBinder service) {
Messenger messenger = new Messenger ( service) ;
Message obtain = Message. obtain ( ) ;
Bundle bundle = new Bundle ( ) ;
bundle. putString ( "key" , "hehehe" ) ;
obtain. setData ( bundle) ;
obtain. replyTo= mes;
try {
messenger. send ( obtain) ;
} catch ( RemoteException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void onServiceDisconnected ( ComponentName name) {
}
} ;
bindService ( intent, connection, BIND_AUTO_CREATE) ;
}
@Override
protected void onDestroy ( ) {
super . onDestroy ( ) ;
unbindService ( connection) ;
}
}
Application
public class MyApp extends Application {
private static final String TAG= "MyApp" ;
public MyApp ( ) {
super ( ) ;
}
@Override
public void onCreate ( ) {
super . onCreate ( ) ;
Log. i ( TAG, "onCreate: " ) ;
}
@Override
public void onTerminate ( ) {
super . onTerminate ( ) ;
Log. i ( TAG, "onTerminate: " ) ;
}
@Override
public void onConfigurationChanged ( Configuration newConfig) {
super . onConfigurationChanged ( newConfig) ;
Log. i ( TAG, "onConfigurationChanged: " ) ;
}
@Override
public void onLowMemory ( ) {
super . onLowMemory ( ) ;
Log. i ( TAG, "onLowMemory: " ) ;
}
@Override
public void onTrimMemory ( int level) {
super . onTrimMemory ( level) ;
Log. i ( TAG, "onTrimMemory: " ) ;
}
}