首页 > 代码库 > java解决 No enclosing instance of type XXX is accessible的问题

java解决 No enclosing instance of type XXX is accessible的问题

有些时候我们要把Activity的一些实现类移到java类里来实现,比如把写以下两个类:

在LifeCircle这个类中:

public class LifeCircle {

	
	public class Mybroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			
		}

	}
}

如果在Activity这样去new:

public class Settings extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_layout);
		LifeCircle lifeCircle = new LifeCircle(this);
		Mybroadcast cast = new Mybroadcast();
	}

}

编译器会报一个错误:

	- No enclosing instance of type LifeCircle is accessible. Must qualify the allocation with an enclosing instance of type LifeCircle (e.g. x.new A() where x is an instance of 
	 LifeCircle).

一种解决方法是把Mybroadcast定义为static class

令一种这样来弄:

package com.example.shoplistdownload;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class LifeCircle {

	
	
	Context mContext;
	private static LifeCircle sInstance;
	private Mybroadcast mBroadcast;
    private Settings mInstance;

	
	LifeCircle(Context context) {
		mContext = context;
		mInstance = (Settings)context;
	}

	public static LifeCircle getIntance(Context context) {
		if (sInstance == null) {
			sInstance = new LifeCircle(context);
		}
		return sInstance;
	}

	public class Mybroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
		}

	}
	
	
	public void registerBroadcaster() {
		mBroadcast = new Mybroadcast();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.example.action");
		mInstance.registerReceiver(mBroadcast, filter);
	}
}

public class Settings extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_layout);
		LifeCircle lifeCircle = new LifeCircle(this);
		lifeCircle.registerBroadcaster();
	}

}


java解决 No enclosing instance of type XXX is accessible的问题