startactivity() not working from inner class that

2019-07-21 23:13发布

问题:

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.