startactivity() not working from inner class that extends ListActivity

和自甴很熟 提交于 2020-01-15 08:38:04

问题


Title basically says it all. The below code doesn't throw any errors, it just doesn't start the new activity. Code below.

I have tried modifying startActivity(new Intent(mCtx, NewActivity.class)); to read startActivity(new Intent(MyListActivity.this, NewActivity.class));

I have been testing this in Eclipse with an AVD.

Any thoughts on this would be appreciated - thanks!

public class MyListActivity extends ListActivity {

private Context mCtx;
MyContentObserver mContentObserver;

@Override
public void onCreate(Bundle onSavedInstance) {
    super.onCreate(onSavedInstance);
    setContentView(R.layout.calls_list);

    mContentObserver = new MyContentObserver(this);

    this.getApplicationContext().getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, mContentObserver);

}

private class MyContentObserver extends ContentObserver {
    private Context mCtx;
    public MyContentObserver(Context ctx ) {
        super(null);
        mCtx = ctx;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        startActivity(new Intent(mCtx, NewActivity.class));
    }
}   
}

回答1:


Possible cause 1

The activity has not been declared.

You have to add the activity to your AndroidManifest.xml

You should add this to your <application> tag in your AndroidManifest.xml:

<activity android:name="package.name.NewActivity">
    <!-- Add an intent filter here if you wish -->
</activity>

Possible cause 2

The onChange method doesn't actually run.

Please use the code below to verify that the onChange method actually gets called:

public class MyListActivity extends ListActivity {
    MyContentObserver mContentObserver;

    @Override
    public void onCreate(Bundle onSavedInstance) {
        super.onCreate(onSavedInstance);
        setContentView(R.layout.calls_list);

        mContentObserver = new MyContentObserver();

        this.getApplicationContext().getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, mContentObserver);
    }

    private class MyContentObserver extends ContentObserver {
        public MyContentObserver() {
            super(null);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.d("MyListActivity.MyContentObserver", "onChange");
            startActivity(new Intent(MyListActivity.this, NewActivity.class));
        }
    }   
}

You could also try launching the activity from onCreate to make sure it can be launched.



来源:https://stackoverflow.com/questions/7217475/startactivity-not-working-from-inner-class-that-extends-listactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!