使用statrtactivity结果并关闭后,第二个活动重新出现

时间:2012-02-21 23:37:22

标签: android

尝试使用我的HTC Desire HD创建一个短信弹出应用程序(只是为了学习),遇到了一个有趣的事情。

通常的故事,我有 BroadcastReceiver ,它会启动服务,然后启动 MainActivity

MainActivity 有一个回复按钮,可以启动 ReplyActivity

我回复后使用setResult将 MainActivity 中的函数运行到 finish(),然后使用 finish() my ReplyActivity

这一切都以id希望关闭,但随后我的 ReplyActivity 再次弹出...我在 MainActivity 中添加了一些日志,但它没有重新调用< strong> ReplyActivity ,因此它会重新出现。

我没有正确使用 finish()功能吗?或者这是 BroadcastReceiver

发生的事情

提前感谢您的任何信息。

修改

感谢您的回复......对于迟到的回复感到抱歉......

我将'singleInstance'添加到我的清单中,但无济于事......

我应该说当我最初收到短信时,我的主要活动正常启动,如果我只是关闭,我不回复一切正常,但如果我做回复,下次我收到短信回复屏幕将在主要人员之前启动,几乎是独立的...也许我没有正确地关闭它

我已附上以下代码...请随时评论任何不正确的做法,因为我还在学习。

再次感谢

主要活动

    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 < 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();
               }

        }

    } 

回复活动

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();        
    }    
}

- 清单文件 -

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

1 个答案:

答案 0 :(得分:0)

看起来正在为ReplyActivity创建多个实例。因此,通过将以下属性应用于清单文件中的ReplyActivity来使其成为单个实例:

<activity android:name=".ReplyActivity" android:launchMode="singleInstance" ... >