-2
我试图创建一个应用程序,该应用程序同时使用了Activity类中的MediaButtonReceiver类和方法。为了让Activity类代码运行,我创建了一个MainActivity的新实例,并试图运行包含我想运行的代码的方法。后来我发现这是不可能的,那么最简单的解决方法是什么?从活动类调用方法时,应用程序崩溃
MainActivity.java
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 main = new external();
}
public void variables(){ //code run when button is pressed in external.java
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);
if (toggleWF.isChecked()) {
if (wifi.isWifiEnabled()) {
wifi.setWifiEnabled(false);
} else {
wifi.setWifiEnabled(true);
}
}
if (toggleBT.isChecked()) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
} else {
mBluetoothAdapter.enable();
}
}
if (toggleNFC.isChecked()){
Class<?> NfcManagerClass;
Method setNfcEnabled, setNfcDisabled;
boolean Nfc = false;
if(mNfcAdapter.isEnabled()) {
try {
NfcManagerClass = Class.forName(mNfcAdapter.getClass().getName());
setNfcDisabled = NfcManagerClass.getDeclaredMethod("disable");
setNfcDisabled.setAccessible(true);
Nfc = (Boolean) setNfcDisabled.invoke(mNfcAdapter);
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e){
}
}
else {
try {
NfcManagerClass = Class.forName(mNfcAdapter.getClass().getName());
setNfcEnabled = NfcManagerClass.getDeclaredMethod("enable");
setNfcEnabled.setAccessible(true);
Nfc = (Boolean) setNfcEnabled.invoke(mNfcAdapter);
} catch (ClassNotFoundException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
if (Nfc == false) {
//add code here if NFC fails to disable/enable
}
}
}
}
}
二等作出新的MainActivity
实例public class external extends MediaButtonReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Button", "pressed");
MainActivity main = new MainActivity();
main.variables();
}
}
您无法执行“MainActivity main = new MainActivity()”。这对Receiver来说是错误的。详细了解如何将数据从接收者发送到活动,然后更新您的观点。 –