android编程5.3.1
为了方便我们从新建个项目,为了发送自定义广播,我们在mainactivity.java旁边建个接受广播的类MyBroadcastReceiver.javapackage com.example.xinwei.mybroadcast;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
}
}
然后在androidmanifest.xml文件里的application标签下注册一下这个广播<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.xinwei.mybroadcast.MY_BROADCAST" />
</intent-filter>
</receiver>
因为这个name是我们自己起的,所以要在mainactivity.java里发送这条广播,先把布局文件activity_main.xml文件修改为<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send broadcast"/>
</LinearLayout>
将mainactivity.java文件修改为package com.example.xinwei.mybroadcast;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.example.xinwei.mybroadcast.MY_BROADCAST");
sendBroadcast(intent);
}
});
}
}
这个文件里的intent.setAction里就是我们起的名字,名字可以随便起,但一定要跟androidmanifest.xml文件里写一样了。这样我们一点击按钮就会出项一个吐司弹框了。效果图
页:
[1]