在等待接收SMS时显示进度对话框

时间:2012-08-14 01:27:53

标签: android sms progressdialog

我想编写一个应用程序,以便在等待接收短信时显示进度对话框。接收SMS时,非空TextView smsReceive将作为解除进度对话框的条件。但它获得了runtimeException。你能告诉我代码中要改变什么。

package cx.opseng.PerfTOLD;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.TextView;

public class Sms extends Activity {
/** Called when the activity is first created. */

static TextView smsReceive;
static TextView smsReceiveChar;

@Override
protected void onCreate(Bundle savedInstanceState) 
{       
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sms);

    Intent i = getIntent();
    // Receiving the Data
    String reg = i.getStringExtra("reg");
    String port = i.getStringExtra("port");

    String smsMessage = reg + port ;

    // Show SMS sent message on screen 
    TextView smsSend = (TextView) findViewById(R.id.smsSend);
    smsSend.setText(smsMessage);
    Log.i("smsSend",String.valueOf(smsSend.getText()));
    // Send SMS message
    SmsManager sm = SmsManager.getDefault();
    String number = "5556";
    sm.sendTextMessage(number, null, smsMessage, null, null);

    ProgressDialog dialog = new ProgressDialog(Sms.this);
    dialog.setMessage("working hard......");
    dialog.setIndeterminate(true);
    dialog.setCancelable(true);
    dialog.show();

    // Receive SMS message
    smsReceive = null;
    smsReceive = (TextView) findViewById(R.id.smsReceive);
    Log.i("smsReceive",smsReceive.getText().toString());
    if (smsReceive.getText().toString() != null) {
        Log.i("smsReceive",smsReceive.getText().toString());
        String smsChar = smsReceive.getText().toString();
        Integer smsChar2 = smsChar.length();
        String smsChar3 = Integer.toString(smsChar2);
        Log.i("smsReceive2",smsChar3);
        smsReceiveChar.setText(smsChar);
        smsReceiveChar = (TextView) findViewById(R.id.smsReceiveChar);
    }

    if (smsReceiveChar.getText().toString() .equals("Message")) {
        dialog.dismiss();
    }

}
public static void updateMessageBox(String msg)
{
    smsReceive.append(msg);
    smsReceiveChar.append(msg);
}    

}

public class SmsReceiver extends BroadcastReceiver{

public void onReceive(Context context, Intent intent)
{
    Bundle bundle=intent.getExtras();

    Object[] messages=(Object[])bundle.get("pdus");
    SmsMessage[] sms = new SmsMessage[messages.length];

    for(int n=0;n<messages.length;n++){
        sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
    }

    for(SmsMessage msg:sms){
        String num = msg.getOriginatingAddress();
        Log.i("SMS sender",num);
        if (num.equals("15555215556")) {
        Sms.updateMessageBox("\nFrom: " + msg.getOriginatingAddress() + 
                "\n" + "Message: " + msg.getMessageBody() + "\n");              }
    }
}
}

logcat如下:

08-14 11:16:56.152: E/AndroidRuntime(2091): FATAL EXCEPTION: main
08-14 11:16:56.152: E/AndroidRuntime(2091): java.lang.RuntimeException: Unable to start activity ComponentInfo{cx.opseng.PerfTOLD/cx.opseng.PerfTOLD.Sms}: java.lang.StringIndexOutOfBoundsException
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.os.Looper.loop(Looper.java:123)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at java.lang.reflect.Method.invoke(Method.java:521)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at dalvik.system.NativeStart.main(Native Method)
08-14 11:16:56.152: E/AndroidRuntime(2091): Caused by: java.lang.StringIndexOutOfBoundsException
08-14 11:16:56.152: E/AndroidRuntime(2091):     at java.lang.String.substring(String.java:1579)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at cx.opseng.PerfTOLD.Sms.onCreate(Sms.java:88)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-14 11:16:56.152: E/AndroidRuntime(2091):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-14 11:16:56.152: E/AndroidRuntime(2091):     ... 11 more

2 个答案:

答案 0 :(得分:1)

我做了一个适合我的例子。

我遇到了因使用线程而导致进度对话无效的问题。

AndroidManifest.xml

<manifest package="com.mw.stackoverflow.example02"
    android:versionCode="1"
    android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>



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

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.mw.stackoverflow.example02;

import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.IntentFilter;

public class MainActivity extends Activity implements SmsUpdater
{
    private static final String TAG = "MainActivity";

    private SmsReceiver mSmsReceiver;

    private class ExaminMessagesTask extends AsyncTask<SmsMessage, Void, Boolean> 
    {
        ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage("Receiving SMS.");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(true);

            mProgressDialog.show();
        }


        protected Boolean doInBackground(SmsMessage... messages) 
        {
            if (messages.length > 0)
            {
                Log.d(TAG, "Showing progress dialog.");

            }

            for (SmsMessage m: messages)
            {
                Log.d(TAG, "Message received");
            }   

            int count = 0;
            for(SmsMessage msg:messages)
            {
                String num = msg.getOriginatingAddress();
                Log.d(TAG, num);

                mProgressDialog.setTitle("Processing message " + (count++));

                try 
                {
                    Thread.sleep(1000);
                }    
                catch (InterruptedException e) 
                {
                }
            }

            return true;
        }

        protected void onProgressUpdate(Integer... progress) 
        {

        }   

        protected void onPostExecute(Boolean result) 
        {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSmsReceiver = new SmsReceiver(this);
    }

    @Override
    protected void onResume() 
    {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(mSmsReceiver, filter);
    }

    @Override
    public void onPause() 
    {
        super.onPause();
        unregisterReceiver(mSmsReceiver);
    }

    @Override
    public void gotSms(final SmsMessage[] m) 
    {
        Log.d(TAG, "OnReceive, number of messages: " + m.length);

        runOnUiThread(new Runnable() 
        {
            public void run() 
            {
                Toast.makeText(MainActivity.this, "SMS received", Toast.LENGTH_SHORT).show();

                new ExaminMessagesTask().execute(m);
            }   
        });
    }

}

SmsReceiver.java

package com.mw.stackoverflow.example02;

import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.telephony.SmsMessage;

class SmsReceiver extends BroadcastReceiver
{
    private static final String TAG = "SMSREC";

    private SmsUpdater mSmsUpdater;

    public SmsReceiver(SmsUpdater u)
    {
        super();
        mSmsUpdater = u;
    }

    public void onReceive(Context context, Intent intent)
    {
        Log.d(TAG, "OnReceive called.");

        Bundle bundle=intent.getExtras();

        Object[] messages=(Object[])bundle.get("pdus");
        SmsMessage[] sms = new SmsMessage[messages.length];
        for(int n=0;n<messages.length;n++)
        {
            sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        mSmsUpdater.gotSms(sms);
    }
}

SmsUpdater.java

package com.mw.stackoverflow.example02;

import android.telephony.SmsMessage;

public interface SmsUpdater 
{
    void gotSms(SmsMessage[] m);
}

答案 1 :(得分:0)

请在第85行查看活动onCreate()的{​​{1}},以获取可能为null的参考。那就是日志说:

09:41:09.993: E/AndroidRuntime(1832): Caused by: java.lang.NullPointerException 08-14 09:41:09.993: E/AndroidRuntime(1832): at cx.opseng.PerfTOLD.Sms.onCreate(Sms.java:85) 08-14 

由于你没有为它发布代码,我无法告诉你哪个对象为空。