android 基础知识总结
学习android中遇到过的问题及一些好的可复用的代码总结:
1,
android利用Socket进行通讯需要注意的事项:
权限问题,需要在androidMainFest文件中添加如下权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
如果上面加完权限还是报错的话则需要在初始化Socket前面加上如下代码
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
2,Activity之间进行切换代码如下:
Intent intent = new Intent(); intent.setClass(First.this, Second.class); startActivity(intent);
3,利用Intent类来进行如下功能实现:
//调用地图坐标
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("geo:37.827500,-122.481670"));
startActivity(intent);
//打开任意网址-这里指百度
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));
startActivity(intent);
//拨打手机号码
Intent intent=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1318196808x"));
startActivity(intent);
4,最烦的就是android里面提示框的编写如下:
private void showDialog(String mess) {
new AlertDialog.Builder(this).setTitle("Message").setMessage(mess)
.setNegativeButton("Sure", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
5,打开手机wifi设置界面代码如下:
private String setWireless() {
String error="";
try {
if(android.os.Build.VERSION.SDK_INT > 10 ){
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
}else {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
}catch (Exception ex)
{
error=ex.toString();
Log.e("error",error);
}
return error;
}
6,socket初始化代码如下:
public static SocketClient getInstance() {
if (instance == null) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
synchronized (ChartInfo.class) {
if (instance == null) {
try {
client = new Socket(IP地址,端口号);
instance = new SocketClient();
} catch (UnknownHostException e) {
Log.e("errorSocketClient_Host",e.getMessage().toString()+"IP"+chartInfo.getIp()+"port:"+chartInfo.getPort());
} catch (IOException e) {
Log.e("errorSocketClient_IOE",e.getMessage().toString()+"IP"+chartInfo.getIp()+"port:"+chartInfo.getPort());
}
}
}
}
return instance;
}
7,Json处理对象代码如下:
JSONObject json = new JSONObject(line);
String method = json.getString("Method");
8,事件消息处理可以用Handler代码如下:
new Handler() {
@Override
public void handleMessage(Message msg) {
处理消息
}
}
9,记录消息日志
代码如下:其中日志级别从高到低分别是ERROR、WARN、INFO、DEBUG。
Log.d("initSocket", "Result:" + obj);
10,加权限要加载
<manifest>与<application>之间,如果加载<application>之下,权限不会生效。
浙公网安备 33010602011771号