在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 }

 

posted @ 2016-03-29 17:39  zhongyinghe  阅读(1018)  评论(0编辑  收藏  举报