无法从onReceive访问AsyncTask中的变量值

时间:2017-10-16 09:17:53

标签: android android-asynctask broadcastreceiver

我有一个Class(BroadcastReceiver)为

public class AlarmReceiverActivity extends BroadcastReceiver 
{

         public  String memtypefrommainactivity="";

         Context mContext;

@Override

  public void onReceive(Context context, Intent intent)

 {

  context=mContext;

  memtypefrommainactivity = intent.getStringExtra("memtypetobroadcast");

 new CheckNewMessages(context).execute(memtypefrommainactivity);

}

And in the same class I have one Asynctask :

protected class CheckNewMessages extends AsyncTask<String,Void,String> {

        public CheckNewMessages(Context context)
        {
            mContext=context;
        }

@Override

protected void onPreExecute() {

        }

        @Override
        public String doInBackground(String... params)
 {

 if(memtypefrommainactivity=="Retired".toString())

{

URL="xyz.com";

}

我没有从引用memtypefrommainactivitymemtypefrommainactivity获得params[0]的值。

1 个答案:

答案 0 :(得分:0)

BroadcastReceiver的生命周期极短。基本上在onReceive()返回后,BroadcastReceiver已经死了。如documentation中所述,您无法从BroadcastReceiver启动异步或长时间运行的活动,并期望获得任何回调。您需要使用Service代替AsyncTask。您的BroadcastReceiver应该开始Service来完成工作,并将必要的参数传递给它。你可能会完全取消BroadcastReceiver并让AlarmManager直接启动Service