今天,我们来讨论安卓四大组件之一广播的基础用法,要了解广播是什么,那么广播是什么呢?
广播的分类与区别——有序广播和无序广播
按照接收者的优先级,逐一传递,优先级最高的接收者先接受,如果不终止此广播,再往下传递
不管有多少接收者,一旦发出了无序广播,所有监听此广播的接收者都能接收到
首先,广播有两种注册方式,一种在清单文件中注册,注册后程序一运行广播就开始监听。一种在代码中注册,根据需求注册注销广播。
我们先看广播的第一种注册方式,首先定义一个广播接受者
public class TestReciver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
}
}
然后再清单文件中注册
<receiver android:name="com.batways.apopo.receiver.TestReciver" >
<intent-filter>
<action android:name="aaa.bbb.ccc" />
<category android:name="android.intent.category.DEFAULT" />
intent-filter>
receiver>
这样,当程序启动的时候,广播就开始监听动作为“aaa.bbb.ccc”的意图。
接下来再看在代码中注册广播
首先在代码中new一个广播接受者
private class UpdateCreditsBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
然后用代码注册:category可以填可以不填
mUpdateCreditsBroadCast = new UpdateCreditsBroadCast();
IntentFilter filter = new IntentFilter("com.batways.apopo_core.service");
//filter.addCategory(Intent.ACTION_DEFAULT);
registerReceiver(mUpdateCreditsBroadCast, filter);
一般而言,在该注册文件的生命周期函数中的起始函数注册广播,在结束函数中注销广播:
unregisterReceiver(mUpdateCreditsBroadCast);
mUpdateCreditsBroadCast = null;
这样,就完成了再代码中广播的注册与注销。
那么,我们发送广播的时候,该怎么弄呢。这里博主提供一个广播工具类吧,一般的都能满足使用了。这里需要特别注意,如果广播注册的时候加了category,这里就需要加,如果没有,这里就不需要加了。
public class BroadcastHelper {
/**
* 发送String 类型的值的广播
* @param context
* @param action
* @param key
* @param value
*/
public static void sendBroadCast(Context context,String action,String key,String value) {
Intent intent = new Intent();
intent.setAction(action);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(key, value);
context.sendBroadcast(intent);
}
public static void sendBroadCast(Context context,String action,String key,int value) {
Intent intent = new Intent();
intent.setAction(action);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(key, value);
context.sendBroadcast(intent);
}
}
附上活动页面代码
package com.example.asus.weatherapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ServiceActivity extends AppCompatActivity {
private Button button1,button2;
public static ImageView imageView;
private Intent intent;
private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
button1= (Button) findViewById(R.id.btn1_service);
button2= (Button) findViewById(R.id.btn2_service);
imageView= (ImageView) findViewById(R.id.img_service);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent=new Intent(ServiceActivity.this,MyService.class);
startService(intent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent=new Intent(ServiceActivity.this,MyService.class);
stopService(intent);
}
});
initReceiver();
}
public void initReceiver(){
myReceiver=new MyReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("com.example.asus.img");
registerReceiver(myReceiver,intentFilter);
}
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
byte[] tu=intent.getByteArrayExtra("tu");
Bitmap bitmap= BitmapFactory.decodeByteArray(tu,0,tu.length);
imageView.setImageBitmap(bitmap);
}
}
}
我们直接在里面定义一个内部类,以便更好的调用广播,下面给上service代码
package com.example.asus.weatherapplication;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by asus on 2018/6/19.
*/
public class MyService extends Service {
private String TAG = "MyService";
private ByteArrayOutputStream os = new ByteArrayOutputStream();
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate...........");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "onBind...........");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand...........");
new Thread(new Runnable() {
@Override
public void run() {
getWebpic();
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy...........");
}
public void getWebpic() {
try {
URL url = new URL("http://img4.duitang.com/uploads/item/201209/14/20120914194440_vJwWL.thumb.700_0.jpeg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputDtream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputDtream);
bitmap.compress(Bitmap.CompressFormat.PNG,100,os);
byte[] tu=os.toByteArray();
Intent intent=new Intent("com.example.asus.img");
intent.putExtra("tu",tu);
sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就可以较为简单的做到Service中发送广播