采用广播的形式接间的调用服务中的方法

来源:互联网 发布:炒股软件ipad版 编辑:程序博客网 时间:2024/04/29 05:38
//服务public class MyService extends Service {    private MyReceiver receiver;    @Override    public IBinder onBind(Intent arg0) {        return null;    }    @Override    public void onCreate() {        System.out.println("oncreate");        super.onCreate();        //采用代码的方式 来注册 广播 接受者        receiver = new MyReceiver();        IntentFilter filter = new IntentFilter();        filter.addAction("com.chain.callmethod");        registerReceiver(receiver, filter);         }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        System.out.println("onstartcommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        //服务销毁时, 取消广播接受者        unregisterReceiver(receiver);        System.out.println("ondestory");        super.onDestroy();    }    /**     * 这是服务里面的一个方法     */    public void methodInService() {        Toast.makeText(this, "哈哈,我是服务里面的方法", 0).show();    }    //自定义广播接收者    private class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            methodInService();//代用服务中的方法                    }    }}
//activitypublic class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    /**     * 作用:     *  1.开启服务     *  2.让服务中的广播接受者就可以处理发出去的广播事件     *  3.广播接受者 根据处理的事件 来调用 服务中的 方法     *      * @param view     */    public void start(View view){        Intent intent = new Intent(this,MyService.class);        //通知框架开启服务。        startService(intent);    }    public void stop(View view){        Intent intent = new Intent(this,MyService.class);        stopService(intent);    }    @Override    protected void onDestroy() {        System.out.println("啊啊啊,我是activity,我挂了");        super.onDestroy();    }    //调用服务里面的方法。不可以自己new服务,调用的服务的方法,必须通过框架得到服务的引用。    public void call(View view){        //发送一个自定义的广播        Intent  intent = new Intent();        intent.setAction("com.chain.callmethod");        sendBroadcast(intent);    }}
0 0