简单的布局只用一个按钮测试控制台输出的内容,如下例图片布局:
运行程序之后,控制台输出内容如下:
创建ReceiverTest类继承BroadcastReceiver。代码内容如下:
package com.bzu.broadcastreceivertest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReceiverTest extends BroadcastReceiver {
public ReceiverTest() {
System.out.println("ReceiverTest()...");
}
@Override
public void onReceive(Context arg0, Intent arg1) {
System.out.println("onReceive()...");
}
}
并在AndroidManifest.xml中对receiver进行注册
<receiver android:name=".ReceiverTest">
<intent-filter>
<action android:name="android.intent.action.EDIT"/>
</intent-filter>
</receiver>
在主要的Activity(MainActivity.java)中编写代码:
package com.bzu.broadcastreceivertest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send=(Button) this.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction(Intent.ACTION_EDIT);
sendBroadcast(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
如上所述,基本就能实现如图的效果。