很简单的UI。点击按钮然后从图片库中选择图片上传(非主线程)。
andriod 主LoadActivity的代码如下:
public class LoadActivity extends Activity { public static final String TAG_STRING="LoadActivity"; private String pathString=null; static final int flag_load=4; private Button button=null; private userUploadService service=new userUploadServiceImpl(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load); button=(Button) this.findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String status = Environment .getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡 Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, flag_load); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.load, menu); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==flag_load) { if(data==null) { Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show(); } else { Uri uri=data.getData(); if (uri==null) { Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show(); } else { String path=null; String[] pojoStrings={MediaStore.Images.Media.DATA}; Cursor cursor=getContentResolver().query(uri, pojoStrings, null, null, null); if(cursor!=null) { int col=cursor.getColumnIndexOrThrow(pojoStrings[0]); cursor.moveToFirst(); path=cursor.getString(col); cursor.close(); } if(path==null) { Toast.makeText(this, "未获得图片路径", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "图片路径为"+path, Toast.LENGTH_LONG).show(); pathString=path; new AlertDialog.Builder(this) .setTitle("提示") .setMessage("你要选择这张图片上传么?") .setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doUpload(); } } ).create().show(); } } } } } private void doUpload() { new Thread(new Runnable() { @Override public void run() { try { InputStream in=new FileInputStream(new File(pathString)); Map<String, String>data=new HashMap<String, String>(); data.put("Name", "liuming"); data.put("Gender", "男"); final String retString=service.userUpload(in, data,pathString); Log.d(TAG_STRING, retString); } catch (Exception e) { e.printStackTrace(); // runOnUiThread(new Runnable() { // public void run() { // Toast.makeText(LoadActivity.this, "上传更新出错", Toast.LENGTH_LONG).show(); // } // }); } } }).start(); } }
<span style="font-family: Arial, Helvetica, sans-serif;">service.userUpload(in, data,pathString)</span>
为处理上传逻辑的接口类实现。
传送门:点击打开链接
时间: 2024-10-12 11:05:50