M
M
math_man2017-02-25 21:48:12
Android
math_man, 2017-02-25 21:48:12

Http request not sent?

Messages are sent safely, reports come in, but when I try to send an HTML request setStatus("2", identificator); , then I get an error.

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.pilig.sms3, PID: 27366
                  java.lang.RuntimeException: Error receiving broadcast Intent { act=SMS_SENT flg=0x10 (has extras) } in com.example.pilig.sms3.End$2@cde38d6
                      ***
                      at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
                      at com.squareup.okhttp.Call.getResponse(Call.java:198)
                      at com.squareup.okhttp.Call.execute(Call.java:80)
                      at com.example.pilig.sms3.End.request(End.java:213)
                      at com.example.pilig.sms3.End.setStatus(End.java:202)
                      at com.example.pilig.sms3.End$2.onReceive(End.java:112)
                      at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:973)
                      at android.os.Handler.handleCallback(Handler.java:815) 
                      at android.os.Handler.dispatchMessage(Handler.java:104) 
                      at android.os.Looper.loop(Looper.java:207) 
                      at android.app.ActivityThread.main(ActivityThread.java:5955) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:801

The file itself (error line - *****)
package com.example.pilig.sms3;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.snmp4j.PDU;
import org.snmp4j.Target;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.util.PDUFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;


/**
 * Created by pilig on 15.01.2017.
 */

public class End extends Activity {
    Button endBtn;
    Drawable red, green;
    TextView endServer, end_login, end_sent, end_get, end_not_get;
    boolean flag = true;
    BufferedReader in;
    String phoneNo, message, id;
    SmsManager sms;
    PendingIntent sentPI, deliveredPI;
    String SENT="SMS_SENT";
    String DELIVERED="SMS_DELIVERED";

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.end);
        getColors();
        endServer = (TextView) findViewById(R.id.end_server);
        end_login = (TextView) findViewById(R.id.end_login);
        end_sent = (TextView) findViewById(R.id.end_sent);
        end_get = (TextView) findViewById(R.id.end_get);
        end_not_get = (TextView) findViewById(R.id.end_not_get);
        end_login.setText(Account.login);
        endServer.setText(Account.server);
        endBtn.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                changeColor();
            }
        });
        sms = SmsManager.getDefault();
        setPI();
        getSMSToSend();
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void changeColor(){
        Drawable button = endBtn.getBackground();
        if(button.equals(green)){
            setFlag(false);
            endBtn.setBackground(red);
        }
        else{
            endBtn.setBackground(green);
            setFlag(true);
            getSMSToSend();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void getColors(){
        endBtn = (Button) findViewById(R.id.end_btn);
        endBtn.setBackground(getResources().getDrawable(R.drawable.oval_button_red));
        red = endBtn.getBackground();
        endBtn.setBackground(getResources().getDrawable(R.drawable.oval_button_green));
        green = endBtn.getBackground();
    }

    public void sendSMS(){

        BroadcastReceiver broadcastReceiverSent = new BroadcastReceiver(){
            String identificator = id;
            @Override
            public void onReceive(Context arg0, Intent arg1){
                switch(getResultCode()){
                    case Activity.RESULT_OK:{
                        setStatus("2", identificator);
                        Account.sent++;
                        incSent();
                        unregisterReceiver(this);
                        break;}
                    case Activity.RESULT_CANCELED:{
                        Toast.makeText(getBaseContext(),"SMS на номер " + phoneNo + " не отправленно", Toast.LENGTH_SHORT).show();
                        unregisterReceiver(this);
                    }
                }
            }
        };

        BroadcastReceiver broadcastReceiverDelivered = new BroadcastReceiver(){
            String identificator = id;
            @Override
            public void onReceive(Context arg0, Intent arg1){

                switch(getResultCode()){
                    case Activity.RESULT_OK:{
                        System.out.println("Identificator=" + identificator);
                        setStatus("3", identificator);
                        Account.get++;
                        incDel();
                        unregisterReceiver(this);
                        //Account.list.remove(this);
                        break;
                    }

                    case Activity.RESULT_CANCELED:{
                        setStatus("4", identificator);
                        Account.notGet++;
                        incNotDel();
                        unregisterReceiver(this);
                        //Account.list.remove(this);
                        break;
                    }
                }
            }
        };

        registerReceiver(broadcastReceiverSent,new IntentFilter(SENT));

        registerReceiver(broadcastReceiverDelivered,new IntentFilter(DELIVERED));

        System.out.println("Login=" + Account.login + "\n"
                +"Password=" +Account.password + "\n" +
                "Phone=" + phoneNo + "\n" +"Message=" + message);
        sms.sendTextMessage(phoneNo,null, message, sentPI, deliveredPI);
    }

    private void setPI(){
        sentPI= PendingIntent.getBroadcast(getBaseContext(),0, new Intent(SENT),0);
        deliveredPI= PendingIntent.getBroadcast(getBaseContext(),0, new Intent(DELIVERED),0);
    }

    public void getSMSToSend()  {


        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
            while(flag){
                String sql = "http://80.252.241.43/telephony/android/get_sms.php?login=" + Account.login + "&password=" + Account.password;
                //System.out.println(sql);
                String text = request(sql);
                if(!text.equals("||")){
                    String phone = text.substring(0, text.indexOf("|"));
                    phoneNo = phone;
                    text = text.substring(text.indexOf("|")+1);
                    String sms = text.substring(0, text.indexOf("|"));
                    message = sms;
                    String idd = text.substring(text.indexOf("|")+1);
                    id=idd;
                    System.out.println("ID="+id);
                    if(!idd.equals("")&&!sms.equals("")&&!phone.equals("")) {
                        sendSMS();
                    }
                }
            }
            }
        });
        thread.start();

    }
    public  void setStatus(String status, String id) {
        String sql = "http://80.252.241.43/telephony/android/send_report.php?login=" +
                Account.login + "&password=" + Account.password + "&id=" + id + "&status=" + status;
        System.out.println("SetStatusRequest=" + sql);
        request(sql);

    }
    public void setFlag(boolean flag){
        this.flag = flag;
    }

    private String request(String sql){
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(sql).build();
*********Response response = client.newCall(request).execute();***************
            return response.body().string();
        } catch (MalformedURLException e) {
            return null;
        } catch (ProtocolException e) {
            return null;
        } catch (IOException ex) {
            return null;
        }
    }

    private void incSent(){
        end_sent.setText(String.valueOf(Account.sent));
    }

    private void incDel(){
        end_get.setText(String.valueOf(Account.get));
    }

    private void incNotDel(){
        end_not_get.setText(String.valueOf(Account.notGet));
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Ne-Lexa, 2017-02-28
@NeLexa

To start working with HTTP, it is desirable to make it a separate service.
Receivers register in onResume() and unregister in onPause()
To send SMS, you need to register permissions in the manifest and for TARGET API >= 23 make a request for their permission.
apparently runs in the main thread, hence the errors climb. You cannot interact with the network from the main thread. Call request(String sql) on a new thread.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question