Android利用廣播在應用程序之間傳遞數據



TestBroadcastA應用如下

MainActivity如下:

package cc.testbroadcasta;
import android.os.Bundle;
import android.app.Activity;
/**
 * Demo描述:
 * 利用廣播在應用程序之間傳遞數據
 * 
 * TestBroadcastA應用中註冊一個廣播接收者.
 * TestBroadcastB應用中發出一個廣播
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	

}

BroadcastReceiverTest如下:

package cc.testbroadcasta;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BroadcastReceiverTest extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
          String name=intent.getStringExtra("name");
          int number=intent.getIntExtra("number", 0);
          System.out.println("接收到廣播 name="+name+",number="+number);
	}

	
	public static void main(String[] args) {

	}

}

main.xml如下:


    

AndroidManifest.xml如下:



    

    
        
            
                

                
            
        
        
        
            
                
            
        
    

TestBroadcastB應用如下

MainActivity如下:

package cc.testbroadcastb;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Intent intent=new Intent();
		//設置Action
		intent.setAction("cc.test");
		//攜帶數據
		intent.putExtra("name", "周星馳");
		intent.putExtra("number", 9527);
		//發送廣播
		sendBroadcast(intent);
	}

	

}

main.xml如下:


    

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *