1. 实现原理,在Service里面注册一个广播接收者, 想要调用的时候app发送出广播,
后台的service里面的广播接收者接收到广播,并调用service里面的方法。
2. 示例代码
MainActivity.java 开启service 发出广播
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); Intent intent = new Intent(this, MyService.class);
startService(intent);
} public void call(View v){
//发出一个特定的广播 service里面的接受器就能接收到,并调用service的方法
Intent intent = new Intent();
intent.setAction("com.kevin.callmethod");
sendBroadcast(intent);
}
MyService.java ,service 内涵广播接收者的 实现与注册
public class MyService extends Service { private MyReceiver myReceiver; @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.kevin.callmethod");
registerReceiver(myReceiver, filter);
super.onCreate();
} @Override
public void onDestroy() {
unregisterReceiver(myReceiver);
super.onDestroy();
} private class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "接受到广播", 0).show();
methodInService();
}
} private void methodInService(){
Toast.makeText(getApplicationContext(), "执行methodInService", 0).show();
} }
xml 里权限注册
<service android:name="com.kevin.servicetest.MyService"/>