0



I m working on SMS feature of android and I can send users location and address via sms to a limited number of contacts as its my apps requirement , now i want to implement Progress dialog so when users click on the send button the progress dialog should be appear and after sending sms to all contacts the progress dialog should disappear .

I searched alot for this but its making me very confuse on how to do it for my application because i am a beginner in android!

can anyone please help me on how to implement onPreExecute(),onPostExecute() and doInBackground() methods in my class, here i am including my java class for sending sms.

package com.example.ghaznavi.myapp;

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.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
import android.content.IntentFilter;


public class SmsHandler{

    Settings setObj=new Settings();
    double latitude,longitude;

    public SmsHandler() {
    }

    public void SendSms(final Context hcontext)
    {
        GPSService mGPSService = new GPSService(hcontext);
        LocationAddress locObj=new LocationAddress();
        mGPSService.getLocation();

        latitude = mGPSService.getLatitude();
        longitude = mGPSService.getLongitude();

        StringBuilder sb = new StringBuilder(160);
        String addd=  locObj.getAddressFromLocation(latitude,longitude,hcontext);

        sb.append("Hi, I m in trouble, Please Help!\n\n");

        if ((latitude != 0.0) && (longitude!= 0.0)) {
            sb.append("Map Link:").append("\n").append("https://maps.google.com/maps?q=").append(latitude).append("%2C").append(longitude).append("\n\n");
        }

        if (addd != null) {
            sb.append("Address: ").append(addd).append("\n\n");
        }
        sb.append( "- My Application");


        setObj.Initialize(hcontext);

        if (setObj.GetContactListCount()!=0)
        {

        for(int i=0;i<setObj.GetContactListCount();i++)
        {
            try
            {
                String SENT = "SMS_SENT";
                PendingIntent sentPI = PendingIntent.getBroadcast(hcontext, 0, new Intent(
                        SENT), 0);
                BroadcastReceiver sendSMS = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(hcontext, "SMS sent Successfully",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                Toast.makeText(hcontext, "Generic failure",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                Toast.makeText(hcontext, "No service",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:
                                Toast.makeText(hcontext, "Null PDU",
                                        Toast.LENGTH_SHORT).show();
                                break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                Toast.makeText(hcontext, "Radio off",
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                };

               SmsManager localSmsManager = SmsManager.getDefault();
                if (sb.toString().length() <= 160) {
                    hcontext.registerReceiver(sendSMS, new IntentFilter(SENT));
                    localSmsManager.sendTextMessage(setObj.GetContactListNumber()[i], null, sb.toString(), sentPI, null);
                } else {
                    hcontext.registerReceiver(sendSMS, new IntentFilter(SENT));
                   localSmsManager.sendTextMessage(setObj.GetContactListNumber()[i], null, sb.toString().substring(0, 159),sentPI, null);
                    localSmsManager.sendTextMessage(setObj.GetContactListNumber()[i], null, sb.toString().substring(160),sentPI, null);
                }

                }
            catch (SecurityException localSecurityException)
            {
                Log.e("Error", "Security Exception, SMS permission denied");
                return;
            }
            }
            }
        else
        {
            Toast.makeText(hcontext,"please select a number",Toast.LENGTH_SHORT).show();
        }
    }
}

Any Help would be much appreciated , Thank you in advance!

Angel
  • 29
  • 1
  • 7
  • Take a look at [this async task](https://github.com/selcukcihan/tahlil/blob/master/app/src/main/java/com/selcukcihan/android/tahlil/HttpPerformingTask.java) which performs an http request. You basically create a class extending `AsyncTask` and then in the `onPreExecute` you would create the progress dialog, which you should then `dismiss` in the `onPostExecute` handler. The `AsyncTask` will call your `SmsHandler` inside `doInBackground` method. – Selçuk Cihan May 10 '16 at 13:28

2 Answers2

0

1) You will need Class which extends AsyncTask

2) Then try foll. snippet -

 public class SendSMS extends AsyncTask<String ,String,String>{
        ProgressDialog pd = new ProgressDialog(MainActivity.this);

       @Override
            protected void onPreExecute() {
                super.onPreExecute();
            //this method executes Before background process done
                pd.setTitle("Please Wait!");
                pd.setMessage("Sending SMS");
                pd.show();
            }

            @Override
            protected String doInBackground(String... params) {
            //Your logic here for sending SMS
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
          //this method executes after completion of background process
             pd.dismiss();  //don't forget to dismiss
            }
}

Hope it will help:)

Onkar Nene
  • 1,359
  • 1
  • 17
  • 23
  • Thank you for your answer , actually the important part is the logic inside doInBackground() method and as you can see in my codes **SendSms** method needs application context and i passed it from mainActivity to this method now here how can i get application context? – Angel May 10 '16 at 14:10
  • You can create nested class for AsyncTask in your current Class. And pass context as "MainActivity.this" or "getApplicationContext()". Hope it will help, Check this for more details - http://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and – Onkar Nene May 11 '16 at 09:10
  • thanks alot I used nested class and I can get the Application context, and I put all the logic of sending sms inside **doInBackground()** method but after loading progress dialog for some seconds its crashing the app and throwing _java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()_ Exception, I wish anybody help me on this for sending sms. – Angel May 11 '16 at 14:19
  • why r u using handler?? Java thread doesn't allow to update data on UI level, for that purpose Handler and AsyncTask are useful in android. – Onkar Nene May 11 '16 at 14:24
  • I didn't used any handler just copied **SendSms()** logic inside **doInBackgroud()** and also it throwing _Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0_ Error_ – Angel May 11 '16 at 20:23
  • IndexOutOfBoundsExeption is getting because array index is null or zero. Just try to debug your code. And u can't copy all login from SendSms into doInBackground(), u have to just copy code which will run on background thread. – Onkar Nene May 12 '16 at 07:38
0

Create an Activity and implement Handler and AsyncTask

public class YourActivity extends AppCompatActivity{

// Constant variables to show progress dialogs...
    private static final int SHOW_PROGRESS = 0x01;
    private static final int STOP_PROGRESS = 0x02;

// On create...
    @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_xml_layout);

   new SendSms().execute();
    }

 // Your asynchronous class..
 public class SendSms extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mHandler.sendEmptyMessage(SHOW_PROGRESS);
        }


        @Override
        protected Void doInBackground(Void... params) {

            // Do your work here

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            mHandler.sendEmptyMessage(STOP_PROGRESS);
        }
    }

  Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SHOW_PROGRESS:

                    if (mProgressDialog == null) {
                        mProgressDialog = Utils.createProgressDialog(YourActivity.this);
                        mProgressDialog.show();
                    } else
                        mProgressDialog.show();
                    mHandler.removeMessages(SHOW_PROGRESS);
                    break;
                case STOP_PROGRESS:

                    if (mProgressDialog != null && mProgressDialog.isShowing())
                        mProgressDialog.dismiss();

                    mHandler.removeMessages(STOP_PROGRESS);
                    break;
    }
};



  protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null && mProgressDialog.isShowing())
            mProgressDialog.dismiss();
    }

// Copy the following methods in your Utils class..

public static ProgressDialog createProgressDialog(Context mContext) {

       // if you want to set style..
        ProgressDialog dialog = new ProgressDialog(mContext,
                R.style.MyProgressDialogStyle);
      // or Otherwise..
        ProgressDialog dialog = new ProgressDialog(mContext);

        try {
            dialog.setCancelable(false);
            dialog.getWindow().setBackgroundDrawable(
                    new ColorDrawable(mContext.getResources().getColor(android.R.color.transparent)));
            dialog.show();
            dialog.setContentView(R.layout.custom_progress_dialog);
        } catch (BadTokenException e) {
            Utils.debug(e.getMessage());
        }
        return dialog;
    }

And custom_progress_dialog in your layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@android:color/transparent">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">


        <ProgressBar
            android:id="@+id/progressBar1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip" />
    </FrameLayout>

</RelativeLayout>

Thats it.. You are good to go. Please let me know if you face any trouble.

Rethinavel
  • 3,912
  • 7
  • 28
  • 49