Second activity re-appearing after using statrtactivityfor result and closed
<p>Trying to create a SMS pop-up app with my HTC Desire HD (just to learn), have encountered an interesting occurrence.</p>

<p>Usual story, i have a <strong>BroadcastReceiver</strong> which starts a <strong>Service</strong> which then starts my <strong>MainActivity</strong>.</p>

<p><strong>MainActivity</strong> has a reply button which starts the <strong>ReplyActivity</strong>.</p>

<p>Once I have replied I use setResult to run the function in the <strong>MainActivity</strong> to <em>finish()</em> and then use <em>finish()</em> my <strong>ReplyActivity</strong>.</p>

<p>It all closes as id hoped, but then my <strong>ReplyActivity</strong> pops up again... I have added some Logs in the <strong>MainActivity</strong> and it doesnt re-call the <strong>ReplyActivity</strong>, so it is re-appearing on its own.</p>

<p>Am i not using the <em>finish()</em> function correctly? Or is this something that happens with the <strong>BroadcastReceiver</strong>?</p>

<p>Thanks for any info in advance.</p>

<p><em><strong>EDIT</em></strong></p>

<p>Thanks for the replies... sorry about the late response...</p>

<p>I added the 'singleInstance' to my manifest but to no avail...</p>

<p>I should say when i initially get a SMS, my main activity fires up correctly and if i just close and i do not reply everything works fine, but if i do reply, the next time i get a SMS the reply screen will fire up before the main one does, almost independently... maybe i am not closing it correctly</p>

<p>I have attached the code below... please feel free to comment on any incorrect practices as i am still learning.</p>

<p>Thanks again</p>

<p><em><strong>Main Activity</em></strong></p>

<pre><code>    package com.b.sms;

    import java.sql.Date;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.List;
    import java.util.TimeZone;
    import android.app.Activity;
    import android.app.PendingIntent;
    import android.content.ContentResolver;
    import android.content.ContentUris;
    import android.content.ContentValues;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.Contacts.People;
    import android.provider.ContactsContract;
    import android.provider.ContactsContract.CommonDataKinds.Phone;
    import android.telephony.SmsMessage;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;

    @SuppressWarnings("deprecation")
    public class Main extends Activity {

        protected static final int CREATE_REQUEST_CODE = 1;

        TextView msgfrom;
        TextView msgtime;
        TextView msgtext;
        ImageView contactpic;

        Bitmap bitmap;
        String body;
        String from;
        String timeSent;
        Date date;
        String photoNo;
        long timestamp;
        String soundUri = "A";
        String ret_soundUri;

        Button close;
        Button delete;
        Button reply;    

        SharedPreferences mPrefs;

        ContentResolver cr;

        String testValue;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mPrefs = getPreferences(MODE_PRIVATE);
            setContentView(R.layout.main);

            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                        Object[] pdus = (Object[]) bundle.get("pdus");
                        SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i &lt; messages.length; i++)         {
                                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                                body = messages[i].getDisplayMessageBody();
                                from = messages[i].getDisplayOriginatingAddress();
                                timestamp = messages[i].getTimestampMillis();
                                date = new Date(timestamp);
                                Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));  
                        cal.setTime(date);  
                        timeSent = "Message received at "+ cal.get(Calendar.HOUR) + ":" 
                            + cal.get(Calendar.MINUTE) 
                            + ":" + cal.get(Calendar.SECOND)  
                            +" "+ (cal.get(Calendar.AM_PM)==0?"AM":"PM");  
                }
            }

             setUpButtons();
             setFields();

        }



        private void setFields() {
            msgfrom = (TextView) findViewById(R.id.msg_from);
            msgtime = (TextView) findViewById(R.id.msg_time);
            msgtext = (TextView) findViewById(R.id.msg_text);

            msgfrom.setText(getSenderName(from));
            msgtime.setText(timeSent);
            msgtext.setText(body);
        }

        private String getSenderName(String sent_number) {
            contactpic = (ImageView) findViewById(R.id.icon);
            cr = getContentResolver();
            Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

            String concatNo = sent_number.substring(4, sent_number.length());

            if (cursor.moveToFirst()) {
                Cursor phones = cr.query(Phone.CONTENT_URI, null, null, null, null);
                while (phones.moveToNext()) {
                    String hasPhoto = phones.getString(phones.getColumnIndex(Phone.PHOTO_ID));
                    photoNo = phones.getString(phones.getColumnIndex(Phone.RAW_CONTACT_ID));
                    int photoId = Integer.parseInt(photoNo);
                    String number = phones.getString(phones.getColumnIndex(Phone.NUMBER)).replace("-", "");;
                    String sender_name = phones.getString(phones.getColumnIndex(Phone.DISPLAY_NAME));
                     if (number.contains(concatNo)) {
                        if (hasPhoto != null) {
                            Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, photoId);
                            Cursor cur = managedQuery(myPerson, null, null, null, null);        
                            Bitmap bitmap = People.loadContactPhoto(this, myPerson, R.drawable.ic_launcher, null);
                            contactpic.setImageBitmap(bitmap);
                        }
                        return sender_name;

                    }
                }
                phones.close();
            }
            cursor.close(); 
            return sent_number;

        }


        private void setUpButtons() {
            close = (Button) findViewById(R.id.button_close);
            delete = (Button) findViewById(R.id.button_delete);
            reply = (Button) findViewById(R.id.button_reply);

            close.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                        markAsRead(false);
                        finish();

                    }
                }
            );

            delete.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                        deleteSMS();
                        finish();
                    }
                }
            );

            reply.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        Intent disIntent2 = new Intent(Main.this, Reply.class);
                        disIntent2.putExtra("to", from);
                        disIntent2.putExtra("photo", photoNo);
                        disIntent2.putExtra("from", getSenderName(from));
                        startActivity(disIntent2);
                        finish();
                    }
                }
            );
        }

        public void deleteSMS() {
            markAsRead(false);
        }


        private void markAsRead(Boolean delete) {
            Uri uriSMSURI = Uri.parse("content://sms/inbox");
            Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
            String str_tstamp = String.valueOf(timestamp);
            while (cur.moveToNext()) {
                String address = cur.getString(cur.getColumnIndex("address"));
                String msgbody = cur.getString(cur.getColumnIndexOrThrow("body"));
                String tStamp = cur.getString(cur.getColumnIndex("date"));
                String markedAsRead = cur.getString(cur.getColumnIndex("read"));
                 String messageId = cur.getString(cur.getColumnIndex("_id"));
                if (tStamp.equals(str_tstamp)) {
                     if (from.equals(address)) {
                        if (msgbody.equals(body)) {
                            if (delete) {
                                // delete
                            } else {
                                if (markedAsRead.equals("0")) {
                                    ContentValues values = new ContentValues();
                                    values.put("READ", 1);
                                    String selection = null;
                                    String[] selectionArgs = null;  
                                    Main.this.getContentResolver().update(
                                            Uri.parse("content://sms/" + messageId), 
                                            values, 
                                            selection, 
                                            selectionArgs);
                                }
                            }
                        }
                     }
                 }
             }
        }    

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == 123) {
                    markAsRead(false);
                    finish();
               }

        }

    } 
</code></pre>

<p><em><strong>Reply Activity</em></strong></p>

<pre><code>package com.b.sms;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class Reply extends Activity {

    Button cancel;
    Button send;

    EditText toSend;
    TextView toField;

    String toNo;    

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        setContentView(R.layout.reply);
        setUpButtons();
        setFields();
    }

    private void setFields() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String to = bundle.getString("from");
            toNo = bundle.getString("to");
            toField = (TextView) findViewById(R.id.msg_to);
            toField.setText("To: " + to);

            ImageView contactpic = (ImageView) findViewById(R.id.icon);
            String photoNo = bundle.getString("photo");
            int photoId = Integer.parseInt(photoNo);
            Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, photoId);
            Cursor cur = managedQuery(myPerson, null, null, null, null);        
            Bitmap bitmap = People.loadContactPhoto(this, myPerson, R.drawable.ic_launcher, null);
            contactpic.setImageBitmap(bitmap);            
        }

    }

    private void setUpButtons() {
        cancel = (Button) findViewById(R.id.button_cancel);
        send = (Button) findViewById(R.id.button_send);

        cancel.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
                }
            }
        );

        send.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                    sendSMS();
                }
            }
        );        
    }

    private void sendSMS() {

        toSend = (EditText) findViewById(R.id.msgTxt);
        PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, Reply.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(toNo, null, toSend.getText().toString(), pi, null);    
        Intent intent = new Intent();       
        setResult(123, intent);
        finish();        
    }    
}
</code></pre>

<p><em><strong>--Manifest file--</em></strong></p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.b.sms"
    android:versionCode="1"
    android:versionName="1.0" &gt;
    &lt;uses-sdk android:minSdkVersion="10" /&gt;
    &lt;uses-permission android:name="android.permission.RECEIVE_SMS"/&gt;
    &lt;uses-permission android:name="android.permission.READ_SMS" /&gt;
    &lt;uses-permission android:name="android.permission.WRITE_SMS" /&gt;    
    &lt;uses-permission android:name="android.permission.READ_CONTACTS"/&gt;
    &lt;uses-permission android:name="android.permission.SEND_SMS"/&gt;
    &lt;uses-permission android:name="android.permission.VIBRATE"/&gt;
    &lt;application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" &gt;
        &lt;activity
            android:label="@string/app_name"
            android:name=".Main"
            android:theme="@style/Theme.D1NoTitleDim" &gt;
        &lt;/activity&gt;
        &lt;activity
            android:label="@string/app_name"
            android:name=".Reply"
            android:theme="@style/Theme.D1NoTitleDim"
            android:launchMode="singleTask" /&gt; 
        &lt;activity
            android:label="@string/app_name"
            android:name=".Sound"/&gt;
        &lt;receiver android:name="SmsReceiver" android:enabled="true"&gt;
               &lt;intent-filter android:priority="2147483647"&gt;
                   &lt;action android:name="android.provider.Telephony.SMS_RECEIVED"&gt;&lt;/action&gt;
               &lt;/intent-filter&gt;
          &lt;/receiver&gt;               
          &lt;service android:name=".SmsReceiverService"/&gt;  
    &lt;/application&gt;
&lt;/manifest&gt;
</code></pre>
