Android之进程通讯——广播

不同进程间的通讯,其实Android的四大组件都可以实现。

日常,我们用广播,在一个独立的app中使用的较多。或者是系统和app之间使用。

在两个自定义的app之间,我们也写个例子,表明广播是很好用的!!

在这里就自定义两个app:BroadCastA(后面称为A)、BroadCastB(后面称为B)。A发送广播,B接收广播。

例子如下:

BroadCastA:

package com.example.broadcasta;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button btnButton=(Button)findViewById(R.id.send);
		btnButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setAction("com.bill99.test");
				intent.putExtra("info", "传递内容");
				sendBroadcast(intent);
			}
		});
		
	}


}


BroadCastB如下:

package com.example.broadcastb;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.widget.Toast;

public class MainActivity extends Activity {

	BroadcastReceiver broadcastReceiver;
	IntentFilter intentFilter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		intentFilter=new IntentFilter();
		intentFilter.addAction("com.bill99.test");
		broadcastReceiver=new MyReceiver();
		registerReceiver(broadcastReceiver, intentFilter);
		
	}

	class MyReceiver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent!=null){
			   if(!TextUtils.isEmpty(intent.getAction())){
				   Toast.makeText(getApplicationContext(), intent.getAction(), Toast.LENGTH_SHORT).show();
			   }
			   if(!TextUtils.isEmpty(intent.getStringExtra("info"))){
				   Toast.makeText(getApplicationContext(), intent.getStringExtra("info"), Toast.LENGTH_SHORT).show();
			   }
			}
		}
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(broadcastReceiver);
	}

    
}

两个app运行后,你在A中点击广播发送,在B中就可以收到广播和传递信息了。


源码:进程间广播通讯源码



猜你喜欢

转载自blog.csdn.net/yangzhaomuma/article/details/50717945