標籤:no enclosing instanc
有些時候我們要把Activity的一些實作類別移到java類裡來實現,比如把寫以下兩個類:
在LifeCircle這個類中:
public class LifeCircle {public class Mybroadcast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {}}}
如果在Activity這樣去new:
public class Settings extends Activity {@Overrideprotected 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 {@Overridepublic 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 {@Overrideprotected 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的問題