调用服务里的方法除了上一篇讲得通过绑定的方式开启服务外还有一种方法:利用广播调用服务里的方法
1.Mainactivity类源代码
public class MainActivity extends Activity {
@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){
//自定义个广播
Intent intent=new Intent();
intent.setAction("com.wq.callmethod");
//发广播
sendBroadcast(intent);
}
}
2.服务的源代码
public class Myservice extends Service {
private Myreceiver receiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
receiver=new Myreceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("com.wq.callmethod");
registerReceiver(receiver, filter);
System.out.println("服务创建了");
super.onCreate();
}
public void onDestroy() {
unregisterReceiver(receiver);
receiver=null;
super.onDestroy();
}
public void Inservice() {
Toast.makeText(this, "我是服务里的方法", 0).show();
}
private class Myreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("我是服务里面的广播接受者");
Inservice();
}
}
}