Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android通過剪切板傳遞實體類數據

android通過剪切板傳遞實體類數據

編輯:關於Android編程

package com.example.androidtest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.text.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.mytv);
    }

	public void onclick(View view){
    	MyData data = new MyData("xi","23");
    	String base64code = "";
    	try {
    		//編碼加密
    		ByteArrayOutputStream bytearray = new ByteArrayOutputStream();
			ObjectOutputStream objectout = new ObjectOutputStream(bytearray);
			objectout.writeObject(data);
			 base64code = Base64.encodeToString(bytearray.toByteArray(),  Base64.DEFAULT);
			objectout.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    	clip.setText(base64code);
    	getclip();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void getclip(){
    	ClipboardManager clip = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    	String msg = clip.getText().toString();
    	MyData mydata = null;
    	//解碼
    	byte[] bytearray = Base64.decode(msg, Base64.DEFAULT);
    	ByteArrayInputStream byteinput = new ByteArrayInputStream(bytearray);
    	try {
			ObjectInputStream out = new ObjectInputStream(byteinput);
			 mydata = (MyData)out.readObject();
		} catch (Exception e) {
			// TODO: handle exception
		}
    	tv.setText(mydata.toString());
    }
    
}
MyData類
package com.example.androidtest;


import java.io.Serializable;


public class MyData implements Serializable {


	private String name;
	private String age;
	public MyData(String n,String age){
		this.name = n;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "name:"+name + " age:"+age;
		
	}
	
	
}
易錯點:
剪切板導入的類是android.text.ClipboardManager;不是android.content.ClipboardManager;
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved