【问题标题】:can i sendBroadcast from class extend AsyncTask?我可以从类扩展 AsyncTask 发送广播吗?
【发布时间】:2011-08-01 04:14:08
【问题描述】:

我有一个扩展 AsyncTask 的类。

当做后台任务完成后,在执行后我得到其他类的静态属性等于做后台的结果,n我想广播它以便其他类中的接收器将是更新接口

这里是 onPostExecuted 的代码

protected void onPostExecute(String result) {
    Log.d(tag, "post executed "+result);
    // do sth here

    if (result != null){
        result = result.trim();
        String temp_result[];
        if ( result.contains("|") ){
            temp_result = result.split("\\|");
            MyGPS.location_info = temp_result[1];//
            Log.d(result, "contains | : "+MyGPS.location_info);
        }else if (result.equalsIgnoreCase("300 OK")){
            Log.d(result, "in 300 OK BUT UNKNOWN : "+ result);
            MyGPS.location_info = "Unknown";
        }else if (result.equalsIgnoreCase("400 ERROR"))
            Log.d(result, "400 ERROR : "+ result);
        else Log.d(result, "else : "+ result);

        //assemble data bundle to be broadcasted
        //myFilteredResponseThread = new Intent(GPS_FILTER);
        myFilteredResponseThread.putExtra("location_info_post", 

MyGPS.location_info);
                    // CAN"T USE SEND BROADCAST METHOD ?


        //myFilteredResponseThread.
        //Log.e(">>GPS_Service<<", "location_info"+MyGPS.location_info);
    }   
}

之后我不能写sendBroadcast方法,这是未定义的whY?

【问题讨论】:

  • 可能是您没有将活动上下文传递给扩展 AsyncTask 的此类。如果您要传递活动上下文,请使用 context.sendbroadcat(intent)
  • 我从我的内部类 GPSListener 调用这个线程 AysnctTask 实现 LocationListener 并且这个内部类在一个类扩展服务中,那么我如何将上下文传递给我的 AsyncTask ?谢谢

标签: android multithreading interface broadcastreceiver


【解决方案1】:

如果我理解正确,以下是解决方案。

class MyService extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

       class GPSListener implements LocationListener{
        public void onLocationChanged(Location arg0) {
            // TODO Auto-generated method stub
                    // you can get context as follow
            MyService.this.getBaseContext().sendBroadcast(new Intent("Hi"));
        }

        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }

        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }

    }

       }

}

【讨论】:

  • 谢谢男孩,自从 MyService.this.getBaseContext().sendBroadcast(new Intent("Hi"));这里有新的 Intent("Hi") cuz i 1 2 向我的 AsyncTask 类发送上下文,对不起,因为我是新手
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多