发送多条短消息时异步任务实现的java进程对话框

ecfdbz9o  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(381)

我在安卓的短信功能工作,我可以通过短信发送用户的位置和地址,作为我的应用程序的要求,数量有限的联系人,现在我想实现进度对话框,所以当用户点击发送按钮的进度对话框应该出现,发送短信后,所有联系人的进度对话框应该消失。
我为此搜索了很多,但它使我非常困惑如何为我的应用程序,因为我是一个初学者在android!
有谁能帮助我在我的类中实现onpreexecute()、onpostexecute()和doinbackground()方法吗?这里我要介绍我的发送短信的java类。

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();
        }
    }
}

如有任何帮助,将不胜感激,提前谢谢!

uklbhaso

uklbhaso1#

创建活动并实现处理程序和异步任务

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();
    }

//复制utils类中的以下方法。。

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;
    }

以及 custom_progress_dialog 在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>

就这样。。你可以走了。如果你遇到任何麻烦,请告诉我。

mefy6pfw

mefy6pfw2#

1) 您将需要扩展asynctask的类
2) 那就试试foll。代码段-

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
            }
}

希望能有帮助:)

相关问题