我正在开发一个相对简单的学校项目登录应用程序。我遇到了将我的应用连接到本地或其他任何网址的问题。我已将互联网访问权限添加到了Android清单文件。Android应用程序无法发布到网址
<uses-permission android:name="android.permission.INTERNET" />
下面的代码在我的主要活动:
public class MainActivity extends Activity {
private EditText username=null;
private EditText password=null;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.ucidText);
password = (EditText)findViewById(R.id.passText);
login = (Button)findViewById(R.id.button1);
//URL CAN BE ANYTHING, WOULD NORMALLY BE 192.168.1.102
if(isConnectedToServer("<-URL to page on locally hosted server->",10)){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Connection failed", Toast.LENGTH_SHORT).show();
}
}
//Function to determine if connection exists
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url); //<--------- I believe the issue has to do with this line.
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
return false;
}
}
}
这是我整个项目的精简版。除了连通性之外,一切都会检查出我直接在手机上运行SDK中的应用程序(Moto X)。有什么建议么?
当您运行此代码时会发生什么?你有任何错误?如果是这样,他们是什么? – 2014-09-29 02:51:59
'catch(Exception e){ return false; }'这可能是一个非常糟糕的想法。如果发生任何问题,您只需忽略异常可以给你的许多细节,找出错误。 – 2014-09-29 02:53:09
除非包含throws声明,否则URL对象将不起作用。 e.printStackTrace()返回 ** java.net.MalformedURLException:未找到协议“URL”** 这是否意味着我必须指定一个http协议? – Phreakradio 2014-09-29 03:07:05