2012-10-03 118 views
1

我想启用/禁用飞行模式编程,但下面的代码是不是working.The应用程序停止运行时意外,我必须forceclose如何启用/禁用飞行模式?

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_airplanemode); 

代码来检查的飞行模式 布尔的IsEnabled =设置的状态.System.getInt( getContentResolver(), Settings.System.AIRPLANE_MODE_ON,0)== 1;

代码切换

Settings.System.putInt(
       getContentResolver(), 
       Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1); 

重装意图

Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 
    intent.putExtra("state", !isEnabled); 
    sendBroadcast(intent); 
     TextView a = new TextView(this); 
     a.setText("AIRPLANE MODE : "+isEnabled); 
     setContentView(a); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_airplanemode, menu); 
    return true; 
} 
+0

提供堆栈跟踪,但很有可能您正在收到SecurityException,因为您无权修改系统设置。 –

+0

Nikolay Elenov:非常感谢你,但我如何提供堆栈跟踪...即时通讯新的android和我试过context.getmenuInflater()但它返回“上下文无法解决” –

+0

连接你的手机到USB,运行终端中的'adb logcat'或者检查Eclipse logcat视图。 –

回答

0

尝试所需的权限添加到您的AndroidManifest.xml文件 尝试增加

android.permission.WRITE_SETTINGS 
2

你需要做的以下。以下内容添加到您的Manifesf文件

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> 

和使用以下几行代码在你的onResume(),

Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 1); 
newIntent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 
newIntent.putExtra("state", true); 
sendBroadcast(newIntent); 

这应该工作,不需要添加context.sendBroadcast()。

相关问题