代码调用广播接收者
1、注册广播
mbcr = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter("com.eastmoney.xxx");
registerReceiver(mbcr, filter);
System.out.println("服务被创建....");
super.onCreate();
}
2、利用广播调用服务中的方法
package com.example.BoadcastService;
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 MyBroadCastReceiver mbcr;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void MethodService(){
Toast.makeText(getApplicationContext(), "服务中的方法被调用", 0).show();
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
mbcr = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter("com.eastmoney.xxx");
registerReceiver(mbcr, filter);
System.out.println("服务被创建....");
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(mbcr);
mbcr=null;
super.onDestroy();
}
private class MyBroadCastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("广播接收者接收到了广播");
MethodService();
}
}
}
package com.example.BoadcastService;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
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.eastmoney.xxx");
sendBroadcast(intent);
}
}