Android Studio:3.0,Android Marshmallow
SendBroadcast:
package com.example.android.sendbroadcast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onsendbroadcast(View view){
Log.v("Inside","OnCLICK");
Intent intent=new Intent();
Log.v("Intent","Created");
intent.setAction("com.example.android.sendbroadcast");
Log.v("Action","Set");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
Log.v("Broadcast","Sent");
}
}
接收广播
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
Log.v("Inside","Reciever");
Toast.makeText(context,"Broadcast Recieved",Toast.LENGTH_LONG).show();
}
}
Android Manifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.android.sendbroadcast"></action>
</intent-filter>
</receiver>
</application>
以上发送广播正常运行。我甚至用日志检查了它。但接收广播没有运行。没有显示toast / log消息。原因是什么?
答案 0 :(得分:0)
广播可以在代码的任何部分使用,您可以在其中获取Context实例。但是,要接收,您必须侦听特定的广播,这可以通过简单的IntentFilter完成,然后您可以使用给定的intent过滤器注册BroadcastReceiver。示例实现如下所示;
要发送的简单广播,我正在使用Context对象在此处发送(片段和其他一些类需要):
Intent in = new Intent(Constants.NETWORK_CHANGE);
in.putExtra(Constants.NETWORK_STATE, Constants.DISCONNECTED);
context.sendBroadcast(in);
下面还详细介绍了一种简单的接收方式:
首先,创建一个BroadcastReceiver实例
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra(Constants.NETWORK_STATE).equals(Constants.DISCONNECTED)) {
//do something here
}
}
};
接下来,使用IntentFilter注册BroadcastReceiver,在onCreate或可执行类的onResume方法(Fragment,Activity,Service或Applcation类)中有一个好处:
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(Constants.NETWORK_CHANGE));
}
IntentFilter是你在aplication中获取适当调用的原因,因为android在设备上发送了很多意图。