-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來說是錯誤的。詳細瞭解如何將數據從接收者發送到活動,然後更新您的觀點。 –