java - 如何在android中的BroadcastReceiver onReceive方法中调用另一个方法?

标签 java android

您好,我正在使用 BroadcastReciever 来跟踪传入消息并将消息发送到数据库以通过 Web 服务进行存储。但是每当我在 onReceive 方法中调用方法时,它都会显示错误消息 unable to start receiver

package com.android.message.alert;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.webservice.call.SendWebservice;

public class MessageListener extends BroadcastReceiver
{
    TextToSpeech tts;
    public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        if(intent!=null && intent.getAction()!=null && ACTION.compareToIgnoreCase(intent.getAction())==0)
        {
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            final SmsMessage[] message = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) 
            {
                message[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }
            SendWebservice.sendToWebservice(message[0].getMessageBody());
        }   
    }
}

任何有关如何在 onReceive 方法中调用另一个方法的帮助都会有所帮助。请帮我解决这个问题。

最佳答案

我在下面的代码中调用广播接收器中的网络服务:

public class CheckTechToolsWebServiceReceiver extends BroadcastReceiver {
  String responsePanelIcon = "";
  private Context mContext;

  @Override
  public void onReceive(Context context, Intent intent) {
    /*
     * System.out.println("Data.isWebServiceConnected" +
     * Data.isWebServiceConnected);
     */mContext = context;
    Data.deviceTime = System.currentTimeMillis();
    try {
      new BackGroundTask().execute(context);
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }

  private void doFailureSettins() {
    Data.isWebServiceConnected = false;
    Data.isInternetConnected = false;
    Data.PANEL_ICON_STATUS = null;
  }

  private class BackGroundTask extends AsyncTask<Context, Context, String> {
    @Override
    protected String doInBackground(Context... params) {
      // TODO Auto-generated method stub
      callServices();
      return null;
    }

    @Override
    protected void onPostExecute(String result) {
      // TODO Auto-generated method stub
      super.onPostExecute(result);
      Iterator<CheckTechToolsServiceAvailaibilityListener> iterator = ConstantLib.WEBSERVICE_STATE_SET
          .iterator();

      while (iterator.hasNext()) {
        CheckTechToolsServiceAvailaibilityListener webServiceStateListener = iterator
            .next();
        webServiceStateListener
            .techToolsWebServiceState(Data.isWebServiceConnected);
      }
    }
  }

  private void callServices() {
    Data.PANEL_ICON_STATUS = responsePanelIcon;
    String panelId = "";
    try {
      if (GetPanelStatusEntityBean.getInstance().getPanelID() != null) {
        panelId = GetPanelStatusEntityBean.getInstance().getPanelID();
      } else {
        panelId = "";
      }

      // System.out.println("onRecieve.....");
      if (CheckNetworkStateClass.isOnline(mContext)) {

        LocationListenerClass.getInstance(mContext)
            .getCurrentLocation();
        HttpPost httpPost = new HttpPost(ConstantLib.BASE_URL
            + "CheckSurepollNetworkConnection");

        String post = "{\"Latitude\":" + "\"" + Data.CURENT_LATITUDE
            + "\"" + "," + "\"PanelID\":" + "\"" + panelId + "\""
            + "," + "\"Longitude\":" + "\"" + Data.CURENT_LONGITUDE
            + "\""
            + " }";

        // Log.v(ConstantLib.LOG1, " post : " + post);
        httpPost.setEntity(new StringEntity(post));

        /*
         * Log.i(ConstantLib.LOG, "URL : = " + ConstantLib.BASE_URL +
         * "CheckSurepollNetworkConnection");
         */httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = ConstantLib.CONNECTION_TIMEOUT;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
            timeoutConnection);
        int timeoutSocket = ConstantLib.SOCKET_TIMEOUT;
        HttpConnectionParams
            .setSoTimeout(httpParameters, timeoutSocket);
        HttpResponse httpResponse = new DefaultHttpClient(
            new BasicHttpParams()).execute(httpPost);
        String responseJson = EntityUtils.toString(httpResponse
            .getEntity());

        // Log.v(ConstantLib.LOG1, " server response : " +
        // responseJson);

        // Get hold of the response entity
        if (responseJson != null) {
          JSONObject jsonObject = new JSONObject(responseJson);
          if (jsonObject.getString(ConstantLib.PANEL_ICON) != null) {
            responsePanelIcon = jsonObject
                .getString(ConstantLib.PANEL_ICON);
            Data.PANEL_ICON_STATUS = responsePanelIcon;
          }

          JSONObject jsonObject1 = new JSONObject(responseJson);
          String responseCode = jsonObject1
              .getString(ConstantLib.RESPONSE_CODE);
          String responseMessage = jsonObject1
              .getString(ConstantLib.RESPONSE_MESSAGE);
          String isSuperPollNetworkAvailable = jsonObject1
              .getString(ConstantLib.IS_SUPERPOLL_NETWORK_AVAILABLE);

          if (isSuperPollNetworkAvailable
              .equalsIgnoreCase(ConstantLib.TRUE)) {
            Data.isWebServiceConnected = true;
          } else {
            Data.isWebServiceConnected = false;
          }
        }
      } else {
        Data.isWebServiceConnected = false;
        Data.isInternetConnected = false;
      }

    } catch (SocketTimeoutException e) {
      doFailureSettins();

    } catch (ConnectTimeoutException e) {
      doFailureSettins();

    } catch (Exception e) {
      doFailureSettins();
    }
  }
}

关于java - 如何在android中的BroadcastReceiver onReceive方法中调用另一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14826486/

相关文章:

java - 为什么我收到这个错误? "Repeated column in mapping for entity"

java - 替换 android 启动器 Activity 动画

android - 多条消息的更新通知

java - Android Webview 应用程序上下文

java - 从 URL Google map 获取经纬度

java - 如何快速滚动卡片 View

java - 如果使用 DWR 和 java 而不是 AJAX 和 PHP,我们必须在 JqGrid 中进行哪些更改?

java - 正则表达式捕获可能存在或可能不存在的一组组

java - 在字符串中查找 CRLF

android - windowContentOverlay "no resource found that matches the given name"