標籤:contex roi encoding launcher enc support android default code
傳遞資料的情境在於不同頁面之間跳轉,需要攜帶資料:簡單資料值指的是String, int等資料, 複雜資料指的是類
1. 使用剪貼簿傳遞簡單資料方法:
第一個頁面裡面放資料操作如下:
1 ClipboardManager clipboardManager = (ClipboardManager);2 getSystemService(Context.CLIPBOARD_SERVICE); 3 String text = "簡單資料";4 clipboardManager.setText(text);5 Intent intent = new Intent(this, OtherActivity.class);6 startActivity(intent);
第二個頁面裡面取資料操作如下:
Intent intent = getIntent(); textView = findViewById(R.id.msgText); myApp = (MyApp) getApplication(); textView.setText("after changed :" + myApp.getText());
其中MyApp是一個類檔案,裡面如下:
public class MyApp extends Application { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; }}
在manifest檔案中加入MyApp類:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.xxx.globalvariables"> <application android:name=".MyApp" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".OtherActivity"></activity> </application></manifest>
2. 使用剪貼簿傳遞複雜資料傳遞方法
第一個頁面存資料的操作如下:
// 方法二:剪貼簿傳遞複雜資料 MyData myData = new MyData("jack", 24); // 將對象轉換為字串 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String base64String = ""; try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(myData); base64String = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT); // 加密 objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } ClipboardManager clipboardManager1 = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager1.setText(base64String); Intent intent1 = new Intent(this, OtherActivity.class); startActivity(intent1);
第二個頁面取資料的方法:
Intent intent = getIntent();
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); String msg = clipboardManager.getText().toString(); ClipBoardTextView = findViewById(R.id.ClipBoardMsgText); // 解碼 byte[] base64_byte = Base64.decode(msg, Base64.DEFAULT); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64_byte); ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(byteArrayInputStream); MyData myData = (MyData) objectInputStream.readObject(); ClipBoardTextView.setText(myData.toString()); } catch (Exception e) { e.printStackTrace(); }
MyData是一個類, 裡麵包括name, age 的get方法和toString()方法, 該類需要實現
Serializable
備忘:由於該類為普通類, 沒有繼承
Application, 所以不用再manifest檔案中配置!
Android 使用剪貼簿傳遞簡單資料及複雜資料的方法