网络呼叫不是从广播接收器中的线程发生的

时间:2014-12-28 16:28:16

标签: android multithreading broadcastreceiver android-service android-networking

我是android的初学者,我正在尝试构建一个识别未接来电的应用程序并发送要存储在远程mysql数据库中的数字。该应用程序能够识别未接来电,但网络呼叫没有发生。我无法在模拟器中运行此应用程序,因此我每次使用设备都会对此应用程序进行更改。

这是我的代码

    package com.example.missedcallverify;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.RequestParams;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.widget.Toast;

    public class IncommingCallReceiver extends BroadcastReceiver
    {

         static boolean ring=false;
         static boolean callReceived=false;
         static String callerPhoneNumber;


         @Override
         public void onReceive(final Context mContext, Intent intent)
         {

                // Get the current Phone State
               String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

               if(state==null)
                   return;

               // If phone state "Rininging"
               if(state.equals(TelephonyManager.EXTRA_STATE_RINGING))
               {           
                         ring =true;
                        // Get the Caller's Phone Number
                        Bundle bundle = intent.getExtras();
                        callerPhoneNumber= bundle.getString("incoming_number");
                        Toast.makeText(mContext, callerPhoneNumber, Toast.LENGTH_LONG).show();
                 }



                // If incoming call is received
               if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
                {
                       callReceived=true;
                       Toast.makeText(mContext, callerPhoneNumber+"hello ", Toast.LENGTH_LONG).show();
                 }


                // If phone is Idle
               if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
               {
                         // If phone was ringing(ring=true) and not received(callReceived=false) , then it is a missed call
                  if(ring==true&&callReceived==false)
                  {
                           Toast.makeText(mContext, "It was A MISSED CALL from : "+callerPhoneNumber, Toast.LENGTH_LONG).show();
                           final Intent intnt = new Intent(mContext,
                                    MyService.class);
                            intnt.putExtra("callerPhoneNumber", callerPhoneNumber);
                            mContext.startService(intnt);

                  }
             }
      }



    }

MyService.java

package com.example.missedcallverify;

import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

  String callerPhoneNumber;

  @Override
  public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();


  }

  @Override
  public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub

    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub

    callerPhoneNumber = intent.getStringExtra(callerPhoneNumber);
    Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
    new Thread(){
      @Override
      public void run() {
        // TODO Auto-generated method stub
        super.run();
        String result = "";
        InputStream is = null;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("no", callerPhoneNumber));
        try{
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost("http://mywebsite.in/confirm_user.php");
              httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
              HttpResponse response = httpclient.execute(httppost);
              HttpEntity entity = response.getEntity();
              is = entity.getContent();
        }catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
        }       
      }
    }.start();
    return super.onStartCommand(intent, flags, startId);
  }

}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.missedcallverify"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <service
            android:name=".MyService"
            android:enabled="true" />

        <!-- Register the Broadcast receiver  -->
        <receiver android:name=".IncommingCallReceiver" android:enabled="true"> 
            <intent-filter>
                    <action android:name="android.intent.action.PHONE_STATE" /> 
                </intent-filter>
           </receiver>
    </application>

</manifest>

我得到了祝酒词,这是一个未接来电:号码。然而,网络呼叫没有发生,我也无法看到日志。我看到甚至服务启动消息。请帮帮我

2 个答案:

答案 0 :(得分:3)

BroadcastReceiver的onReceive方法仅用于短同步操作 - 一旦执行方法的最后一行,上下文就会死亡。因此,您从此处开始的任何异步操作(例如后台线程)都将立即死亡。

如果您想通过广播执行长期操作,您应该使用服务来执行此操作。在onReceive中,您应该开始服务,服务将运行这些操作。

详细了解here(主要是接收器生命周期位)。

答案 1 :(得分:0)

您是否在清单上申请了Internet权限?