2017-04-21 118 views
0

我试图在MediaButtonReceiver类中使用findViewByIdgetApplicationContextgetSystemService,但没有一种方法可以解决。我想我需要通过上下文的MediaButtonReceiver类,以允许使用这些功能,但我无法弄清楚如何在非活动类中使用findViewById

类尝试使用方法:

public class external extends MediaButtonReceiver { 

private Context context; 

Activity activity; 
public external(Context context,Activity activity){ 
    this.context=context; 
    this.activity=activity; 
} 



@Override 
public void onReceive(Context context, Intent intent) { 
    Log.d("Button", "pressed"); 




    final ToggleButton toggleWF = (ToggleButton) findViewById(R.id.WiFi_toggle); 
    final ToggleButton toggleBT = (ToggleButton) findViewById(R.id.BT_toggle); 
    final ToggleButton toggleNFC = (ToggleButton) findViewById(R.id.NFC_toggle); 
    NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext()); 
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); 

主要活动:

public class MainActivity extends Activity { 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ((AudioManager) getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName(
      this, 
      external.class)); 


    external External = new external(MainActivity.this,this); 

} 

} 
+0

请解释一下你需要什么来实现的,只要我能理解,你想火广播接收器吧?从广播接收器需要显示的UI获得用户输入?在这种情况下,你正在引发广播接收器的方式是错误的。对这个问题,请发表评论,那么我可以给你的答案代码。 –

+0

你并不需要一个框架,并且活动。任何活动我一切已经上下文 –

+0

@ChethanShetty基本上我试图让这个当按下外部媒体按钮,该应用程序将检查开关按钮的状态,然后利用这些国家/变量的代码之后。外部按钮代码工作,我只是需要让这个上面列出的方法,方法是使用在MediaButtonReceiver类或我可以把这些方法在MainActivity如果我能找到一种方法,使这些变量在MediaButtonReceiver类访问。我只是不知道如何去解决这些解决方案。 –

回答

0

你可以使用这样的布局。

 Dialog dialog = new Dialog(context); 
     dialog.setContentView(R.layout.your_layout_xml); 


     // set the dialog components - text, image and button 
     TextView text = (TextView) dialog.findViewById(R.id.text); 
0

不要做接收机长时间运行的操作,你可以打开像context.startActivity的onReceive方法(新的意向书(CONTEX,Activity.class对话活动或活动)和活动类,你可以执行任何你想。也不要使用构造活动对象传递给接收器

相关问题