java解決 No enclosing instance of type XXX is accessible的問題

來源:互聯網
上載者:User

標籤: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的問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.