在Service中使用广播接受者

1、清单文件

 <service android:name="com.example.callmethod.MyService"></service>

2、开启服务和发送广播

 1 package com.example.callmethod;
 2 
 3 import android.os.Bundle;
 4 import android.app.Activity;
 5 import android.content.Intent;
 6 import android.view.Menu;
 7 import android.view.View;
 8 
 9 public class MainActivity extends Activity {
10 
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_main);
15         Intent intent = new Intent(this, MyService.class);
16         startService(intent);
17     }
18 
19     public void call(View view){
20         //发送广播
21         Intent intent = new Intent();
22         intent.setAction("com.example.callMethod");
23         sendBroadcast(intent);
24     }
25 
26 }

3、实现Service

 1 package com.example.callmethod;
 2 
 3 import android.app.Service;
 4 import android.content.BroadcastReceiver;
 5 import android.content.Context;
 6 import android.content.Intent;
 7 import android.content.IntentFilter;
 8 import android.os.IBinder;
 9 import android.widget.Toast;
10 
11 public class MyService extends Service {
12 
13     private MyRecervice recervice;
14     @Override
15     public IBinder onBind(Intent intent) {
16         // TODO Auto-generated method stub
17         return null;
18     }
19     
20     @Override
21     public void onCreate() {
22         //采用代码的方式实现广播接受者,所以不需要再清单文件中进行配置
23         recervice = new MyRecervice();
24         IntentFilter filter = new IntentFilter();
25         filter.addAction("com.example.callMethod");//说明它接收的action
26         registerReceiver(recervice, filter);
27         super.onCreate();
28     }
29 
30     @Override
31     public void onDestroy() {
32         // TODO Auto-generated method stub
33         unregisterReceiver(recervice);
34         recervice = null;
35         super.onDestroy();
36     }
37 
38     public void methodInService(){
39         Toast.makeText(this, "我是服务的方法", 0).show();
40     }
41     
42     private class MyRecervice extends BroadcastReceiver{
43         //当接收到广播后,调用的方法
44         @Override
45         public void onReceive(Context context, Intent intent) {
46             // TODO Auto-generated method stub
47             System.out.println("我是服务内部的广播接收者,接收了广播事件");
48             methodInService();
49         }
50         
51     }
52 
53 }

 

转载于:https://www.cnblogs.com/zhongyinghe/p/5333833.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值