Android——BroadcastReceiver里怎么执行耗时操作
Posted Yawn__
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android——BroadcastReceiver里怎么执行耗时操作相关的知识,希望对你有一定的参考价值。
一个进程如果正在执行BroadcastReceiver的 onReceive() 方法,就会被当做一个前台进程,不易被系统杀死。
当 onReceive() 执行完毕,BroadcastReceiver 就不再活跃,其所在进程会被系统当做一个空进程,随时有可能被系统杀死。
所以在 onReceive 方法中执行异步请求操作,很可能请求结果没有返回,BroadcastReceiver就被系统回收了。
在BroadcastReceiver里执行耗时操作,一般有两种写法:
- (1)由当前BroadcastReceiver启动新的Service,在新的Service中操作
- (2)新起一个线程执行异步操作
(1)Service
在android 开发中,一般耗时操作都会尽可能交给 Service 做,我们知道,Service 是工作在主线程的,所以不能直接在里面执行耗时操作,一般需要开启子线程去做,而IntentService 是 Service 的子类,正是可以用来处理异步请求的,同Service 有两个好处:一是其内部开启了一个异步处理工作线程 HandlerThread ,不用我们自己去 new Thread 了;二是不需要考虑什么时候关闭该 Service,当完成所有的任务后会自动关闭。
先来看一下怎么自定义IntentService
// 该方法是在 HandlerThread异步消息处理线程的消息队列中取出消息进行处理,当所有的msg处理完,messageQueue为空,IntentService 就会调用 stopSelf 方法停止
@Override
protected void onHandleIntent(@Nullable Intent intent)
Log.d(TAG, "IntentService is handling intent msg");
if ("com.xss.startIntentService".equals(intent.getAction()))
String msg = intent.getStringExtra("data");
Log.d(TAG, Thread.currentThread().getName());
Log.d(TAG, "Msg received from main handler thread: broadcast send = " + msg);
// 处理耗时请求
SystemClock.sleep(5000);
Log.d(TAG, "Is Broadcast ANR ?");
// 子线程处理消息后,给主线程发消息,说"我执行完了"
Message mainMsg = new Message();
mainMsg.what = 0x22;
mainMsg.obj = "Msg from child handler thread: I have done !";
// 使用广播将处理耗时操作的数据发送给主线程
Intent intent0 = new Intent(BroadcastTestActivity.ACTION_FROM_INTENTSERVICE);
intent0.putExtra("data_from_intent_service", "Msg from MyIntentService: I have done !");
sendBroadcast(intent0);
// 如果消息队列为空,就会直接结束Service,接着执行onDestroyed方法
举个例子:
public class BroadcastTestActivity extends AppCompatActivity implements View.OnClickListener
public static final String TAG = "MainThread";
public static final String ACTION_SEND_MSG_BY_MYINTENTSERVICE = "com.xss.download.by.myIntentService";
public static final String ACTION_FROM_INTENTSERVICE = "com.xss.download.intentService";
private Button btn_send_intent_service;
private TextView tv_msg, tv_msg_intent_service;
private DownloadBroadcastReceiver downloadBroadcastReceiver;
class DownloadBroadcastReceiver extends BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent)
tv_msg.append("--onReceive: action = " + intent.getAction());
tv_msg.append("\\n");
String data = intent.getStringExtra("data");
// 3. 执行耗时操作
if (ACTION_SEND_MSG_BY_MYINTENTSERVICE.equals(intent.getAction()))
tv_msg_intent_service.append("--onReceiver: process time-consuming by IntentService !");
tv_msg_intent_service.append("\\n");
// 使用 IntentService 处理耗时操作,并且通过广播回传处理成功的回调
sendMsgByIntentService(context, data);
else if (ACTION_FROM_INTENTSERVICE.equals(intent.getAction()))
// 回调结果:Service通过广播发送数据,更新UI
tv_msg_intent_service.append("\\n");
tv_msg_intent_service.append("--onReceiver: received data from IntentService !");
tv_msg_intent_service.append("\\n");
tv_msg_intent_service.append("--data = " + intent.getStringExtra("data_from_intent_service"));
tv_msg_intent_service.append("\\n");
/**
* 策略二:使用 IntentService处理
* @param data
*/
private void sendMsgByIntentService(Context context, String data)
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction("com.xss.startIntentService");
intent.putExtra("data", data);
context.startService(intent);
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast_test);
// 1. 注册广播
registerBroadcast();
initView();
private void registerBroadcast()
downloadBroadcastReceiver = new DownloadBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("");
intentFilter.addAction(ACTION_SEND_MSG_BY_MYHANDLERTHREAD);
intentFilter.addAction(ACTION_SEND_MSG_BY_MYINTENTSERVICE);
intentFilter.addAction(ACTION_FROM_INTENTSERVICE);
registerReceiver(downloadBroadcastReceiver, intentFilter);
private void initView()
tv_msg = (TextView) findViewById(R.id.tv_msg);
tv_msg_handler_thread = (TextView) findViewById(R.id.tv_msg_handler_thread);
btn_send_my_handler_thread = (Button) findViewById(R.id.btn_send_my_handler_thread);
tv_msg_intent_service = (TextView) findViewById(R.id.tv_msg_intent_service);
btn_send_intent_service = (Button) findViewById(R.id.btn_send_intent_service);
btn_send_my_handler_thread.setOnClickListener(this);
btn_send_intent_service.setOnClickListener(this);
private void sendBroadcast(String action)
// 2. 发送广播
Intent intent = new Intent(action);
intent.putExtra("data", "hello, This is a msg from broadcast to send to you !");
sendBroadcast(intent);
@Override
public void onClick(View v)
switch (v.getId())
case R.id.btn_send_intent_service:
tv_msg_intent_service.append("--onClick: begin to send broadcast !--\\n");
sendBroadcast(ACTION_SEND_MSG_BY_MYINTENTSERVICE);
break;
default:
break;
@Override
protected void onDestroy()
super.onDestroy();
unregisterReceiver(downloadBroadcastReceiver);
stopService(new Intent());
(2)子线程
在API11之前,onReceive()方法中不能使用子线程来解决耗时的工作:
- 因为BroadcastReceiver的生命周期很短,子线程可能还没有结束BroadcastReceiver就先结束了.
- BroadcastReceiver一旦结束,此时BroadcastReceiver所在的进程很容易在系统需要内存时被优先杀死.
- 因为它属于空进程(没有任何活动组件的进程).如果它的宿主进程被杀死,那么正在工作的子线程也会被杀死.
- 所以采用子线程来解决是不可靠的.
在API11之后,可以用goAsync方法,然后在新开一个线程去执行:
- API11以后可以调用goAsync()方法,这个方法会返回一个PendingResult对象,android系统会认为OnReceive()方法还没有执行完成直到调用PendingResult.finish(),
- 所以可以调用goAsync方法后,新开一个线程去执行耗时操作,执行完后调用PendingResult.finish()方法。这里的耗时的操作也不能超过10秒.
public void onReceive(final Context context, final Intent intent)
final PendingResult result = goAsync();
wl.acquire();
AsyncHandler.post(new Runnable()
@Override
public void run()
handleIntent(context, intent);//耗时操作
result.finish();
);
public final class AsyncHandler
private static final HandlerThread sHandlerThread = new HandlerThread("AsyncHandler");
private static final Handler sHandler;
static
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
public static void post(Runnable r)
sHandler.post(r);
private AsyncHandler()
以上是关于Android——BroadcastReceiver里怎么执行耗时操作的主要内容,如果未能解决你的问题,请参考以下文章