在Service中使用广播接受者

时间:2023-12-15 12:02:26

1、清单文件

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

2、开启服务和发送广播

 package com.example.callmethod;

 import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View; 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 view){
//发送广播
Intent intent = new Intent();
intent.setAction("com.example.callMethod");
sendBroadcast(intent);
} }

3、实现Service

 package com.example.callmethod;

 import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.Toast; public class MyService extends Service { private MyRecervice recervice;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} @Override
public void onCreate() {
//采用代码的方式实现广播接受者,所以不需要再清单文件中进行配置
recervice = new MyRecervice();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.callMethod");//说明它接收的action
registerReceiver(recervice, filter);
super.onCreate();
} @Override
public void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(recervice);
recervice = null;
super.onDestroy();
} public void methodInService(){
Toast.makeText(this, "我是服务的方法", 0).show();
} private class MyRecervice extends BroadcastReceiver{
//当接收到广播后,调用的方法
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("我是服务内部的广播接收者,接收了广播事件");
methodInService();
} } }