本文主要是介绍Android Ordered Broadcast 有序广播,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码设置IntentFilter:
IntentFilter intentFilter = new IntentFilter();intentFilter.setPriority(15);intentFilter.addAction("shortcut.song.com.myapplication.MY_BROADCAST");intentFilter.addCategory("android.intent.category.LAUNCHER");
MyBroadcast .java
package shortcut.song.com.myapplication;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;/*** Created by Administrator on 2017/8/16 0016.*/public class MyBroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context, "接收到的Intent Action为:"+intent.getAction() +" \n 消息内容:"+intent.getStringExtra("msg"), Toast.LENGTH_SHORT).show();Bundle bundle = new Bundle();bundle.putString("first", "Fisrt BroadcastReceiver set message.");// 将bnudle放入结果中setResultExtras(bundle);// 取消Broadcast的继续传播//abortBroadcast();}
}
MyBroadcastReceiver2 .java
package shortcut.song.com.myapplication;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;/*** Created by Administrator on 2017/8/17 0017.*/public class MyBroadcastReceiver2 extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Bundle bundle = getResultExtras(true);// 解析前一个BroadcastReciver所存入的key为fisrt的消息String first = bundle.getString("first");Toast.makeText(context,"上一个Broadcast存入的消息为:" + first, Toast.LENGTH_SHORT).show();}
}
AndroidManifest.xml
<receiver android:name=".MyBroadcast"><intent-filter android:priority="20"><action android:name="shortcut.song.com.myapplication.MY_BROADCAST" /></intent-filter></receiver><receiver android:name=".MyBroadcastReceiver2"><intent-filter android:priority="0"><action android:name="shortcut.song.com.myapplication.MY_BROADCAST" /></intent-filter></receiver>
package shortcut.song.com.myapplication;import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;public class OrderedBroadcastActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_ordered_broadcast);}public void sendOrderedBroadCast(View v) {Intent intent = new Intent();intent.setAction("shortcut.song.com.myapplication.MY_BROADCAST");intent.putExtra("msg", "First message.");// 发送有序广播sendOrderedBroadcast(intent, null);}
}
运行效果:
这篇关于Android Ordered Broadcast 有序广播的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!