Android开发中,常用的代码片段包括:,,1. 获取系统版本信息:String version = android.os.Build.VERSION.RELEASE;
,2. 检查网络连接状态:ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
,3. 启动新Activity:Intent intent = new Intent(this, TargetActivity.class); startActivity(intent);
,4. 设置TextView内容:textView.setText("Hello World!");
,5. 注册广播接收器:registerReceiver(receiver, new IntentFilter("com.example.MY_ACTION"));
,6. 发送广播:sendBroadcast(new Intent("com.example.MY_ACTION"));
,7. 创建对话框:AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Title").setMessage("Message").setPositiveButton("OK", null).create().show();
,8. 读取SharedPreferences中的值:SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE); String value = preferences.getString("key", "defaultValue");
,9. 保存数据到SharedPreferences:SharedPreferences.Editor editor = preferences.edit(); editor.putString("key", "value"); editor.apply();
,10. 获取当前时间戳:long timestamp = System.currentTimeMillis();