0

我想在 BroadcastReacevier 中运行多个活动。但它不起作用,只有两个活动正在开始。SMSRxDialog 每次都被调用,但 SaveMessages 和 ShowMessages 没有被调用。他们中的任何一个同时开始。其次是所谓的。如果我启动 SaveMessage 然后 showMessage 然后 sahow 消息开始但没有开始保存消息。或反之亦然。在开始另一个活动之前是否需要停止第一个活动。

提前致谢。

以下是代码:

package screenmagic.myfirstapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MQTTMessageReceiver extends BroadcastReceiver  
{  
private static final String TAG = "MQTTMessageReceiver";
@Override   
public void onReceive(Context context, Intent intent)  
{  
    Bundle notificationData = intent.getExtras();  
    String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);  
    String newData  = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);              
    Log.v("REG", "new Topic :" + newTopic);
    Log.v("REG", "new Data: "+ newData);


    Intent chatIntent = new Intent();
    chatIntent.setClass(context, SaveMessages.class);
    context.startActivity(chatIntent);  

    Intent di = new Intent();
    di.setClass(context, SMSRxDialog.class);
    di.putExtra(SMSRxDialog.SMS_FROM_ADDRESS_EXTRA, "MQTT");
    di.putExtra(SMSRxDialog.SMS_FROM_DISPLAY_NAME_EXTRA, newTopic);
    di.putExtra(SMSRxDialog.SMS_MESSAGE_EXTRA, newData);
    di.putExtra(SMSRxDialog.DIALOG_TITLE, "Chat Received");
    context.startActivity(di);  

    Intent msgIntent = new Intent();
    msgIntent.setClass(context, ShowMessages.class);
    context.startActivity(msgIntent);   

    }

}  

我在这里调用了三个活动,它们是:

package screenmagic.myfirstapp;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ShowMessages extends Activity {
 DatabaseHandler db;
 private static final String TAG = "ShowMessages";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   db = new DatabaseHandler(this);
   Log.i("REGISTER", " Calling showChatMessages");
   showChatMessages();

}

public void showChatMessages(){
      Log.i(TAG, "Message recieved:  showChatMessages" );
        Log.d(TAG, "Getting data from database ..");
        Log.d("Reading: ", "Reading all contacts..");

      List<Messages> message = db.getAllMessages();       

        for (Messages msg : message) {
            String log = "Id: "+msg.getID()+"Topic: "+msg.getTopic()+" ,From Host: " + msg.getFrom() + " ,Message: " + msg.getMessage();
                // Writing Contacts to log
        Log.d("Record: ", log);
        Log.d(TAG, "Data retrieved from database ..");
        }

}
}

另一个是:

package screenmagic.myfirstapp;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class SaveMessages extends Activity {
 DatabaseHandler db;
 private static final String TAG = "SaveMessages";

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, " Creating  DatabaseHandler object");
    db = new DatabaseHandler(this);
    Log.i(TAG, "Created  DatabaseHandler object");
    saveChatMessage();

}

public void saveChatMessage(){
      Log.i(TAG, "Message recieved:  saveChatMessage" );
      Log.d("Insert: ", "Inserting ..");
      db.addMessage(new Messages(18,"txtbox.in123", "asmita","test MQTT message from Asmita"));
      Log.d("Insert: ", "Data inserted ..");

}
}

第三次活动 ::

package screenmagic.myfirstapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.speech.tts.TextToSpeech.OnInitListener;
//import android.speech.tts.TextToSpeech;
//import android.speech.tts.TextToSpeech.OnInitListener;


public class SMSRxDialog extends Activity implements OnInitListener {
 private static final String TAG = "SmsReceivedDialog";

    private static final int DIALOG_SHOW_MESSAGE = 1;

    public static final String SMS_FROM_ADDRESS_EXTRA = "com.example.android.apis.os.SMS_FROM_ADDRESS";
    public static final String SMS_FROM_DISPLAY_NAME_EXTRA = "com.example.android.apis.os.SMS_FROM_DISPLAY_NAME";
    public static final String SMS_MESSAGE_EXTRA = "com.example.android.apis.os.SMS_MESSAGE";
    public static final String DIALOG_TITLE = "screenmagic.myfirstapp.DIALOG_TITLE";

   // private TextToSpeech mTts;

    private String mFromDisplayName;
    private String mFromAddress;
    private String mMessage;
    private String mFullBodyString;
    private String mDialogTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDialogTitle = getIntent().getExtras().getString(DIALOG_TITLE);

        mFromAddress = getIntent().getExtras().getString(SMS_FROM_ADDRESS_EXTRA);
        mFromDisplayName = getIntent().getExtras().getString(SMS_FROM_DISPLAY_NAME_EXTRA);
        mMessage = getIntent().getExtras().getString(SMS_MESSAGE_EXTRA);

         mFullBodyString = String.format(
                getResources().getString(R.string.sms_speak_string_format),
                mFromDisplayName,
                mMessage);

        extracted();
        //mTts = new TextToSpeech(this, this);

    }

    private void extracted() {
        showDialog(DIALOG_SHOW_MESSAGE);
    }

    public void onInit(int status) {
    /*if (status == TextToSpeech.SUCCESS) {
            int result = mTts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e(TAG, "TTS language is not available.");
            } else {
                mTts.speak(mFullBodyString, TextToSpeech.QUEUE_ADD, null);
            }
        } else {
            // Initialization failed.
            Log.e(TAG, "Could not initialize TTS.");
        }

        */
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_SHOW_MESSAGE:
            return new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_email)
                    .setTitle(mDialogTitle)
                    .setMessage(mFullBodyString)
                    .setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        public void onCancel(DialogInterface dialog) {
                            finish();
                        }
                    }).create();
        }
        return null;
    }

}

数据库代码是::

package screenmagic.myfirstapp;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "SMSMAGIC2";

// Contacts table name
private static final String TABLE_NAME = "chatmessages";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FROM = "fromHost";
private static final String KEY_TOPIC = "topic";
private static final String KEY_MESSAGE = "message";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FROM + " TEXT,"
            + KEY_TOPIC + " TEXT," +  KEY_MESSAGE + " TEXT )";
    Log.d("Insert: ", "Table create query:: "+CREATE_CONTACTS_TABLE);

    db.execSQL(CREATE_CONTACTS_TABLE);
    Log.d("Insert: ", "Table created ..");

}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    Log.d("Upgrade: ", "Called onUpgrade function"+TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    Log.d("Insert: ", "Dropped Table created .."+TABLE_NAME);
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addMessage(Messages message) {

    Log.d("Insert: ", "addMessage function  ..");

    ContentValues values = new ContentValues();

    values.put(KEY_MESSAGE, message.getMessage()); // message 
    values.put(KEY_TOPIC, message.getTopic()); // topic Name
    values.put(KEY_FROM, message.getFrom()); // from
    values.put(KEY_ID, message.getID()); //Id 

    Log.d("Insert: ", "Message :"+ message.getMessage());
    Log.d("Insert: ", "topic :"+ message.getTopic());
    Log.d("Insert: ", "from :"+ message.getFrom());
    Log.d("Insert: ", "id :"+ message.getID());

    Log.d("Insert: ", "values added to ContentValues.");
    SQLiteDatabase db = this.getWritableDatabase();
    Log.i("Insert: ", "Object Created from SQLiteDatabase.");

    try {
            db.insert(TABLE_NAME, null, values);
            Log.d("Insert: ", "Inserted Row..");
            db.close();
            Log.d("Insert: ", "Closing database connection.");
      } catch (Exception e) {
//           /   Toast.makeText(this, "misfunctioning open" + e.toString(),Toast.LENGTH_LONG).show();
            Log.d("Insert: ", "Exception Row.."+e.getMessage());

        }

}

// Getting All Contacts
public List<Messages> getAllMessages() {
    List<Messages> msgList = new ArrayList<Messages>();

    String selectQuery = "SELECT  * FROM " + TABLE_NAME;
    Log.d("Query :: ", "selectQuery ::"+selectQuery);
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Messages message = new Messages();
            message.setID(Integer.parseInt(cursor.getString(0)));
            message.setTopic(cursor.getString(1));
            message.setFrom(cursor.getString(2));
            message.setMessage(cursor.getString(3));
            msgList.add(message);
        } while (cursor.moveToNext());
    }
    return msgList;
}

}
4

1 回答 1

1

从接收者那里开始 3 项活动没有意义,因为您不知道行为会是什么。

总是做 A -> B -> C -> D 而不是直接做 A-> B,C,D

where A is your Reciever and B,C,D are your activities

于 2012-12-03T09:44:18.437 回答