⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mmsexamplecontainer.cpp

📁 Symbian c++ 的彩信发送接收实例
💻 CPP
字号:
/*
* ============================================================================
*  Name     : CMMSExampleContainer from MMSExampleContainer.h
*  Part of  : MMSExample
*  Created  : 04.11.2006 by Forum Nokia
*  Implementation notes:
*     Initial content was generated by Nokia Series 60 AppWizard.
*  Version  : 2.0
*  Copyright: Nokia Corporation
* ============================================================================
*/

// INCLUDE FILES
#include "MMSExampleContainer.h"
#include "MMSExample.hrh"
#include "MMSExamplePanics.pan"

#include <eikrted.h>  				//RichText Editor
#include <txtrich.h> 				// CRichText
#include <mtclreg.h>              	// for CClientMtmRegistry 
#include <msvids.h>               	// for Message type IDs
#include <mmsclient.h>            	// for CMmsClientMtm
#include <AknQueryDialog.h>       	// for CAknTextQueryDialog
#include <barsread.h>            	// for TResourceReader
#include <f32file.h>				
#include <coeutils.h>			  	// Check the file exist

#include <CMsvMimeHeaders.h>		//Attachemt mimeheader
#include <MMsvAttachmentManager.h>	//Attachment manager

#include <PathInfo.h>
#define KDirPictures		PathInfo::ImagesPath()
#define KPhoneRootPath		PathInfo::PhoneMemoryRootPath()

//Constants
const TInt KMaxAddressLength = 20;  // maximum length for a recipient address
_LIT( KFileName, "mmsexample.jpg" ); 	//Attachment file name

/*
-------------------------------------------------------------------------------
    CMMSExampleContainer::ConstructL()
    Description: 2nd phase Constructor.
-------------------------------------------------------------------------------
*/
void CMMSExampleContainer::ConstructL(const TRect& aRect)
    {
    CreateWindowL();
    
    iRecipient = HBufC::NewL(KMaxAddressLength);// for recipient address (gsm number)
    // Create CMsvSession
    iSession = CMsvSession::OpenAsyncL(*this);// new session is opened asynchronously
	
	// Create RichTextEditor
	iRtEd = new (ELeave) CEikRichTextEditor;
	// Setting RichTextEditor flags
	iRtEd->SetAknEditorCase(EAknEditorLowerCase);
	// Fixed case
	iRtEd->SetAknEditorFlags
		(
		EAknEditorFlagFixedCase| //Set up the Allowed Cases
		EAknEditorFlagEnableScrollBars // Set up the scroller
		);
	iRtEd->ConstructL(this,0,0,CEikEdwin::ENoAutoSelection|CEikEdwin::EReadOnly);
	iRtEd->SetFocus(ETrue);
	iRtEd->UpdateScrollBarsL();
	
	SetRect(aRect);
    ActivateL();
    
    SizeChanged();
    }

/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::CompleteConstructL()
    Creates client MTM registry when session is ready for use. 
    This completes model construction and is called after 'server
    ready' event is received after async opening of CMsvSession.
-----------------------------------------------------------------------------
*/
void CMMSExampleContainer::CompleteConstructL()
    {
    // We get a MtmClientRegistry from our session
    // this registry is used to instantiate new mtms.
    iMtmReg = CClientMtmRegistry::NewL(*iSession);
    iMmsMtm = (CMmsClientMtm*) iMtmReg->NewMtmL( KUidMsgTypeMultimedia );

	_LIT(KSessionOpen, "Server session opened.");
	EchoL(KSessionOpen);
    }

// ---------------------------------------------------------
// CRTEContainer::SizeChanged()
// Called by framework when the view size is changed
// ---------------------------------------------------------
//
void CMMSExampleContainer::SizeChanged()
    {
    TRect rect = Rect();
    		
	TRect ScrollBarRect = iRtEd->ScrollBarFrame()->VerticalScrollBar()->Rect();
	//In 3rd edition CEikRichTextEditor draw the view for the whole rect and
	//the scrollbar doesn't show. That is a reason why CEikRichTextEditor Width() is
	//rect.Width()-ScrollBarRect.Width()
	iRtEd->SetExtent(TPoint(0,0), 
		TSize(rect.Width()-ScrollBarRect.Width(), rect.Height()));
    }
    
/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::~CMMSExampleAppUi()
    Destructor.
-----------------------------------------------------------------------------
*/
CMMSExampleContainer::~CMMSExampleContainer()
    {    
	delete iRtEd;
    delete iRecipient;
    delete iMmsMtm;
    delete iMtmReg;
    delete iMsvEntry;
    delete iSession;    // session must be deleted last (and constructed first)
    }
    
/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::HandleSessionEventL()

    Receives session events from observer and calls event handling functions. 
    Note that if additional session event handlers are defined 
    in the session, they are called before this function (as this is the
    main session observer).
    The type of event is indicated by the value of aEvent. The 
    interpretation of the TAny arguments depends on this type. 
-----------------------------------------------------------------------------
*/
void CMMSExampleContainer::HandleSessionEventL(TMsvSessionEvent aEvent, TAny* aArg1, TAny* aArg2, TAny* /*aArg3*/)
    {

    switch (aEvent)
        {
            // This event tells us that the session has been opened
        case EMsvServerReady:
            CompleteConstructL();       // Construct the mtm registry & MMS mtm
            break;
			
		case EMsvEntriesCreated:
			//Listening when new message is arrived in inbox
            if (aArg2 &&  *(static_cast<TMsvId*>(aArg2)) == KMsvGlobalInBoxIndexEntryId)
                {
                CMsvEntrySelection* entries = static_cast<CMsvEntrySelection*>(aArg1);
                if( entries->Count() >= 1 )
                    {
                    _LIT(KMessageReceived, "Message received.");
					EchoL(KMessageReceived);
					_LIT(KSOpenInbox, "Open inbox.");
					EchoL(KSOpenInbox);
                    }
                else
                    {
                    Panic(EMmsEngineInternal);
                    }
                }
        default:
            break;
        }
    }
    
/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::Draw()
    Simple Draw method.
-----------------------------------------------------------------------------
*/
void CMMSExampleContainer::Draw(const TRect& aRect) const
    {
    CWindowGc& gc = SystemGc();
    gc.SetPenStyle(CGraphicsContext::ENullPen);
    gc.SetBrushColor(KRgbWhite);
    gc.SetBrushStyle(CGraphicsContext::ESolidBrush);
    gc.DrawRect(aRect);
    }

/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::InitializeCommunicationsL()
    Initialize a new message and ask the user for a recipient address.
    Return values:      ETrue or EFalse
-----------------------------------------------------------------------------
*/
TBool CMMSExampleContainer::InitializeCommunicationsL()
    { 
    // First the recipients address
    // we get it from a data query dialog.
    TBuf<20> addr = iRecipient->Des();

    CAknTextQueryDialog* telNumDialog = CAknTextQueryDialog::NewL(addr, CAknQueryDialog::ENoTone);

    if (!telNumDialog->ExecuteLD(R_MMSEXAMPLE_TEL_NUMBER_DIALOG))
        return EFalse;

    iRecipient->Des() = addr; // Note that the user can give both numeric and textual data in the query dialog,
                              // so the address can be a GSM number or an e-mail address.

    // set up a new message 
    return CreateNewMessageL();
    }

/*
-----------------------------------------------------------------------------
    CMMSExampleContainer::CreateNewMessageL()
    Creates a new message server entry and set up default values.
    In case the attachment file does not found method return EFalse
    otherwise ETrue.
    There are differenses how to add attachment file between 2nd and 3rd edition. 
-----------------------------------------------------------------------------
*/
TBool CMMSExampleContainer::CreateNewMessageL()
	{
	_LIT(KCreatingMessage, "Creating message.");
	EchoL(KCreatingMessage);
	
    // - CMsvEntry accesses and acts upon a particular Message Server entry.
    // - NewL() does not create a new entry, but simply a new object to access an existing entry.
    // - It takes in as parameters the client's message server session,
    //   ID of the entry to access and initial sorting order of the children of the entry. 
    CMsvEntry* entry = CMsvEntry::NewL(*iSession, KMsvGlobalOutBoxIndexEntryId ,TMsvSelectionOrdering());
    CleanupStack::PushL(entry);

    // Set context to the parent folder (Outbox)
    iMmsMtm->SwitchCurrentEntryL( entry->EntryId() );
    
    iMmsMtm->CreateMessageL( iMmsMtm->DefaultServiceL()  );
    CleanupStack::PopAndDestroy(); // entry
    
    // Setting recipients
    // use this to add the "To" recipients.
    iMmsMtm->AddAddresseeL( iRecipient->Des() );
    
    //Setting message subject
    _LIT(KMessageSubject, "MMS Example");
    iMmsMtm->SetSubjectL(KMessageSubject);
    
    // Message consists of one image
    #ifndef __HARDCODED_PATHS__ //3rd and 2nd edition
        TFileName attachmentFile(KPhoneRootPath);
        attachmentFile.Append(KDirPictures);
        TFileName fileName(KFileName);
        attachmentFile.Append(KFileName);
    #else//1st edition
        TFileName attachmentFile(KDirPictures);
        attachmentFile.Append(KFileName);
    #endif 
    
    TMsvEntry ent = iMmsMtm->Entry().Entry();
    // Set InPreparation to false
    ent.SetInPreparation(EFalse);
    ent.SetVisible(ETrue);            // mark as visible, after this the message can be seen in Outbox and, after sending, in Sent folder.
    iMmsMtm->Entry().ChangeL(ent);    // Commit changes

      	//Save the changes
        iMmsMtm->SaveMessageL();
        
      	//Opening store
      	CMsvStore* store = iMmsMtm->Entry().EditStoreL();
    	CleanupStack::PushL(store);

    	RFile attachment;
    	//open attachment file
    	TInt error = attachment.Open( CCoeEnv::Static()->FsSession(), attachmentFile, EFileShareReadersOnly | EFileRead );
    	CleanupClosePushL( attachment );
    	
    	//Check that the attachment file exist.
    	if(error != KErrNone)
    		{
    		_LIT(KFileNotFound, "Attachment file not found!");
    		EchoL(KFileNotFound);
    		EchoL(attachmentFile);
    		
    		attachment.Close();
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		return EFalse;
    		}
    	else
    		{
    		//mime header
    		CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
    		CleanupStack::PushL( mimeHeaders );   
    		mimeHeaders->SetSuggestedFilenameL(fileName);

       	 	// Represents a single attachment and information about the attachment
     		CMsvAttachment* attaInfo = 
    			CMsvAttachment::NewL( CMsvAttachment::EMsvFile );
    		CleanupStack::PushL( attaInfo );

    		//Mime Type
    		_LIT8(KMimeType, "image/jpeg");
    		TBufC8<10> mimeType(KMimeType);	

        	TMsvAttachmentId attachId = KMsvNullIndexEntryId;

    		//Attachment file must be an public folder (e.g. c:\Data\images)
        	iMmsMtm->CreateAttachment2L(
                                    *store,
                                    attachment,
                                    mimeType,
                                    *mimeHeaders,
                                    attaInfo,
                                    attachId );

        	CleanupStack::Pop( attaInfo ); // attaInfo
    		CleanupStack::PopAndDestroy(mimeHeaders); // mimeHeaders
    		
    		_LIT(KCreatingComplete, "Message created.");
    		EchoL(KCreatingComplete);
    		
    		store->CommitL();
    		attachment.Close();
    	
    		CleanupStack::PopAndDestroy(); // attachment
    		CleanupStack::PopAndDestroy(); // store
    		}
		    
    return ETrue;
	}
	
/* 
-----------------------------------------------------------------------------
    CMMSExampleContainer::SendMessageL()
    Sends the message.
    Return values: ETrue or EFalse
-----------------------------------------------------------------------------
*/
TBool CMMSExampleContainer::SendMessageL()
    {
	_LIT(KSendingMessage, "Sending message.");
	EchoL(KSendingMessage);

	// Start sending the message via the Server MTM to the MMS server
    CMsvOperationWait* wait = CMsvOperationWait::NewLC();
    wait->iStatus = KRequestPending;
    CMsvOperation* op = NULL;
   	op = iMmsMtm->SendL(wait->iStatus );
    wait->Start();
    CleanupStack::PushL( op );
    CActiveScheduler::Start();

    // The following is to ignore the completion of other active objects. It is not
    // needed if the app has a command absorbing control.
    while( wait->iStatus == KRequestPending )
        {
        CActiveScheduler::Start();
        }

	#ifdef __WINS__
	_LIT(KSendingComplete, "Sending complete.");
	EchoL(KSendingComplete);
	_LIT(KOpenSent, "Open sent folder.");
	EchoL(KOpenSent);
	#endif

    CleanupStack::PopAndDestroy(2); // op, wait
	
    return ETrue;
    }

// ---------------------------------------------------------
// CRTEContainer::CountComponentControls() const
// ---------------------------------------------------------
//
TInt CMMSExampleContainer::CountComponentControls() const
    {
    return 1; // return number of controls inside this container
    }

// ---------------------------------------------------------
// CRTEContainer::ComponentControl(TInt aIndex) const
// ---------------------------------------------------------
CCoeControl* CMMSExampleContainer::ComponentControl(TInt aIndex) const
    {
    switch ( aIndex )
        {
        case 0:
			return iRtEd;
        default:
            return NULL;
        }
    }

// ---------------------------------------------------------
// OfferKeyEventL() 
// Distribute the key event to the Editor
// ---------------------------------------------------------
TKeyResponse CMMSExampleContainer::OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType)
	{
	if (iRtEd->IsFocused())
		{
		return iRtEd->OfferKeyEventL(aKeyEvent, aType);	
		}
	else
		{
		return EKeyWasNotConsumed;
		}
	}
	
// ---------------------------------------------------------
// EchoL(const TDesC &aMessage)
// Display information message.
// ---------------------------------------------------------
void CMMSExampleContainer::EchoL(const TDesC &aMessage)
	{
    iRtEd->RichText()->InsertL(0, aMessage);
    iRtEd->RichText()->InsertL(aMessage.Length(), CEditableText::ELineBreak);
    iRtEd->UpdateAllFieldsL();
    iRtEd->UpdateScrollBarsL();
	}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -