broadcastReceiver传值的⽤法详情
注意:⼴播的发送都是全局发送的,跨应⽤的,所以我们在使⽤的时候不能使⽤下⾯的action传参数,需要添加参数
intent.setComponent(new ComponentName("com.archermind.fm", "com.archermind.fm.MusicWidgetBroadcastReceiver"));
第⼀步:⾃定义⼴播
安卓intent用法public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = Extras();
int count = Int( "count" );
Log.v("MainActivity", "Count is " + count);}}
第⼆步:声明和注册⼴播
private MyReceiver receiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView( R.layout.activity_main );
//启动服务
startService(new Intent(MainActivity.this, MyService.class));
//注册⼴播接收器
receiver=new MyReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("li.demobroad.MyService");
isterReceiver(receiver,filter);
}
@Override
protected void onDestroy() {
//结束服务
stopService(new Intent(MainActivity.this, MyService.class));
}
第三步:补充服务端
public class MyService extends Service {
private int count = 0;
private boolean tag=false;
@Override
public void onCreate() {
new Thread(new Runnable() {
@Override
public void run() {
while (!tag) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
Log.v("MyService", "Count is " + count);
//发送⼴播
Intent intent=new Intent();
intent.putExtra("count", count);
intent.setAction("li.demobroad.MyService"); sendBroadcast(intent);}}
}).start();
}
@Override
public IBinder onBind(Intent intent) {return null;}
@Override
public void onDestroy() {
count=0;
tag = true;
Log.v("MyService", "on destroy");
}}
第三步:清单⽂件中注册服务(注意资源回收 ⼴播和服务)<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
tools:ignore="WrongManifestParent"></service>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论