Back button not working after displaying Contact

2020-07-11 04:58发布

问题:

I am playing with the "Clickable List Items" code from Pro Android 4. The code is basically:

public class MainActivity extends ListActivity implements OnItemClickListener
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        CursorLoader loader = new CursorLoader(this, Contacts.CONTENT_URI, null,
            null, null, Contacts.DISPLAY_NAME + " ASC");
        Cursor cursor = loader.loadInBackground();

        String[] columns = new String[] { Contacts.DISPLAY_NAME };
        int[] views = new int[] { android.R.id.text1 };

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
            android.R.layout.simple_list_item_1, cursor, columns, views, 
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        setListAdapter(adapter);

        getListView().setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
    {
        Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id);
        Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
        startActivity(intent);
    }
}

This all works fine. I see the list of contacts and when I tap a name it opens the address book for that person.

The problem is that the Back button does not work from the address book. According to the book , tapping the back button from the address book should bring me back to the above Activity. But instead I am taken back to the home screen.

My app is still running, when I switch to it manually I get back to it and the list view is at the proper previous scroll position, etc.

This is on Android 4.1.1. I'm wondering if there is something extra I should implement to make this work?

This is the Manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.contactslist"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

回答1:

Sounds like your Activity stack is getting messed up somehow. Try adding the following before you start your call to startActivity(intent)

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);