应用程序在收到消息时崩溃

时间:2013-04-10 07:10:53

标签: android broadcastreceiver

我有以下代码,之前我添加了一些代码来保存收到的短信。

package com.example.smsTest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {
    private SQLiteAdapter mySQLiteAdapter;
@Override
public void onReceive(Context context, Intent intent) {
    Message message = null;

       Bundle extras = intent.getExtras();
       if (extras == null)
       return;

       Object[] pdus = (Object[]) extras.get("pdus");
       for (int i = 0; i < pdus.length; i++) {
          SmsMessage SMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
          String sender = SMessage.getOriginatingAddress();
          String body = SMessage.getMessageBody().toString();

          message = mySQLiteAdapter.createMessage(body);

          // A custom Intent that will used as another Broadcast
         Intent in = new Intent("SmsMessage.intent.MAIN").
         putExtra("get_msg", sender+":"+body);

         // To display a Toast whenever there is an SMS.
         Toast.makeText(context,body,Toast.LENGTH_LONG).show();

         //You can place your check conditions here(on the SMS or the sender)            
         //and then send another broadcast 
         context.sendBroadcast(in);

        // This is used to abort the broadcast and can be used to silently
        // process incoming message and prevent it from further being 
        // broadcasted. Avoid this, as this is not the way to program an app.
        this.abortBroadcast();
        }
     }
 }

我添加的导致此崩溃的代码如下:

private SQLiteAdapter mySQLiteAdapter;
Message message = null;
message = mySQLiteAdapter.createMessage(body);

这是createMessage函数的代码:

public Message createMessage(String message) {
    String[] columns = new String[]{KEY_ID, KEY_CONTENT};

    ContentValues values = new ContentValues();
    values.put(KEY_CONTENT, message);
    long insertId = sqLiteDatabase.insert(MYDATABASE_TABLE, null,
    values);
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE,
            columns, KEY_ID + " = " + insertId, null,
    null, null, null);
    cursor.moveToFirst();
    Message newMessage = cursorToMessage(cursor);
    cursor.close();
    return newMessage;
}

我不知道错误来自哪里。

2 个答案:

答案 0 :(得分:2)

看起来你没有实例化mySQLiteAdapter。您必须在访问它之前进行实例化。

答案 1 :(得分:0)

请评论此代码行,

 Toast.makeText(context,body,Toast.LENGTH_LONG).show();

我认为这样可行,我在后台服务上遇到了与UI操作相同的问题,请使用代码,或者用Log.d(用日志替换)来记录信息

相关问题