Data transmission between Android applications

Source: Internet
Author: User

In some projects, multiple applications exist, so data transmission between applications becomes inevitable. How can we implement data transmission between applications? We know that data transmission across activities can be achieved through the combination of Bundle and Intent. Can this method be used for data transmission between applications? The answer is yes!

Bundle can be used to transmit data, such as direct data transmission, serialized data transmission, and packaged data transmission. The following is the transfer from the TransDataA application to the TransDataB application.





During direct data transmission, we transmit image data. During serialization transmission and packaging transmission, the corresponding structure information is transmitted. The following code is implemented:

MainActivity. java of the TransDataA Project

package com.example.transdataa;import com.example.data.DirectData;import com.example.data.SerialData;import com.example.data.ParcelData;import com.kitsp.contentsp.IntentSp;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button _directTrans_button = null;private Button _serialTrans_button = null;private Button _pracelTrans_button = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Init();}private void Init() {FetchUIControls();BindingEvents();}private void FetchUIControls() {_directTrans_button = (Button) findViewById(R.id.activity_main_directTrans);_serialTrans_button = (Button) findViewById(R.id.activity_main_serialTrans);_pracelTrans_button = (Button) findViewById(R.id.activity_main_ParcelTrans);}private void BindingEvents() {if(_directTrans_button!=null){_directTrans_button.setOnClickListener(new OnClickListenerEx());}if (_serialTrans_button != null) {_serialTrans_button.setOnClickListener(new OnClickListenerEx());}if (_pracelTrans_button != null) {_pracelTrans_button.setOnClickListener(new OnClickListenerEx());}}private class OnClickListenerEx implements OnClickListener {@Overridepublic void onClick(View v) {Bundle bundle = null;switch (v.getId()) {case R.id.activity_main_directTrans:{bundle=DirectGenerateData();break;}case R.id.activity_main_serialTrans: {bundle = SerializeData();break;}case R.id.activity_main_ParcelTrans: {bundle = ParcelableData();break;}default: {break;}}TransData(bundle);}private Bundle DirectGenerateData(){Bundle bundle = new Bundle();Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.test);bundle.putParcelable(DirectData.KEY, bitmap);return bundle;}private Bundle SerializeData() {SerialData serialData = new SerialData();serialData.SetSerialNo("123456789");serialData.SetWeight(180.82);Bundle bundle = new Bundle();bundle.putSerializable(SerialData.KEY, serialData);return bundle;}private Bundle ParcelableData() {ParcelData parcelData = new ParcelData();parcelData.SetAccount("Test");parcelData.SetPassword("ABCDEFG");parcelData.SetAge(25);Bundle bundle = new Bundle();bundle.putParcelable(ParcelData.KEY, parcelData);return bundle;}private void TransData(Bundle bundle) {if (bundle == null) {return;}Intent intent = new Intent();ComponentName cn = new ComponentName("com.example.transdatab","com.example.transdatab.MainActivity");if (cn != null) {intent.setComponent(cn);intent.putExtras(bundle);startActivity(intent);}}}}
Note:

1. Data is added to Intent as Bundle. Remember to put textras (bundle) in Intent ). This is a required step to add data to the Intent, and may sometimes be forgotten.

2. Use Intent to start another application across applications. The ComponentName method is used to start another application. \

3. There is an upper limit when using Intent to transmit data, otherwise the application will be stuck or black screen. What is the specific upper limit? There are many sayings on the Internet, including 40 kb, kb, and 1 MB. The actual test result is about KB. My conclusion is that it may be related to the specific device.

MainActivity. java of the TransDataB Project

package com.example.transdatab;import android.app.Activity;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.os.Bundle;import android.widget.TextView;import com.example.data.DirectData;import com.example.data.SerialData;import com.example.data.ParcelData;public class MainActivity extends Activity {private SerialData _serialData = null;private ParcelData _parcelData = null;private Bitmap _bitmap=null;private TextView _info_textView = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Init();}private void Init() {FetchUIControls();InitParams();InitUI();}private void InitParams() {try {Intent intent = getIntent();if (intent == null) {_info_textView.setText("Intent is null");return;}if(intent.hasExtra(DirectData.KEY)){_bitmap=intent.getParcelableExtra(DirectData.KEY);}if (intent.hasExtra(SerialData.KEY)) {_serialData = (SerialData) intent.getSerializableExtra(SerialData.KEY);_info_textView.setText("MachineData");}if (intent.hasExtra(ParcelData.KEY)) {_info_textView.setText("RegisterData");_parcelData = (ParcelData) intent.getParcelableExtra(ParcelData.KEY);}} catch (Exception e) {_info_textView.setText("Exception");}}private void FetchUIControls() {_info_textView = (TextView) findViewById(R.id.activity_main_info);}private void InitUI() {if (_info_textView == null) {return;}String info = "";if(_bitmap!=null){BitmapDrawable bitmapDrawble= new BitmapDrawable(MainActivity.this.getResources(), _bitmap); bitmapDrawble.setBounds(0, 0, _bitmap.getWidth(),_bitmap.getHeight());_info_textView.setCompoundDrawables(null, bitmapDrawble, null, null);}if (_serialData != null) {info = "SerialData\nSerialNo=" + _serialData.GetSerialNo() + "\nWeight="+ _serialData.GetWeight() + "\n";}if (_parcelData != null) {info = "ParcelData\nAccount=" + _parcelData.GetAccount() + "\n" + "Password="+ _parcelData.GetPassword() + "\n" + "Age="+ _parcelData.GetAge() + "\n";}_info_textView.setText(info);}}
Note:

1. At the end of the received data, first obtain the Intent, then determine whether the corresponding KEY exists, and then unbind the data.

2. When obtaining directly transmitted data, use intent. getParcelableExtra to obtain data.

When transmitting serialized and packaged data in TransDataA and TransDataB, you must use the same KEY and the same class. Otherwise, the data cannot be parsed. Here, they share classes in the TransData project. below is the code.

TransData project DirectData. java

package com.example.data;public class DirectData {public final static String KEY="{56896229-BFCD-4630-B1EF-4D8FA6CA90FE}";}
Note: To directly transmit data, you only need a unique KEY. KEY uses GUID to ensure uniqueness. You can also name it yourself, as long as it can ensure uniqueness.

SerialData. java of the TransData Project

package com.example.data;import java.io.Serializable;public class SerialData implements Serializable {public static final String KEY="{1D7D9EF2-06F6-4A55-9DF6-293471209D15}";/** *  */private static final long serialVersionUID = 1464294135398038125L;private String _serialNo="";private double _weight_kg=0;public void SetSerialNo(String serialNo){_serialNo=serialNo;}public String GetSerialNo(){return _serialNo;}public void SetWeight(double weight_kg){_weight_kg=weight_kg;}public double GetWeight(){return _weight_kg;}}
Note:

1. Implement Serializable.

2. Each variable must have the corresponding Set and Get methods.

ParcelData. java of the TransData Project

package com.example.data;import android.os.Parcel;import android.os.Parcelable;public class ParcelData implements Parcelable {public final static String KEY="{00D2DF54-B448-415F-AB7C-E0C6B6D3E608}";private String _account="";private String _password="";private int _age=0;public void SetAccount(String account){_account=account;}public String GetAccount(){return _account;}public void SetPassword(String password){_password=password;}public String GetPassword(){return _password;}public void SetAge(int age){_age=age;}public int GetAge(){return _age;}@Overridepublic int describeContents() {// TODO Auto-generated method stubreturn 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {// TODO Auto-generated method stubdest.writeString(_account);dest.writeString(_password);dest.writeInt(_age);}public static final Parcelable.Creator<ParcelData> CREATOR=new Creator<ParcelData>() {@Overridepublic ParcelData createFromParcel(Parcel source) {ParcelData registerData=new ParcelData();registerData._account=source.readString();registerData._password=source.readString();registerData._age=source.readInt();return registerData;}@Overridepublic ParcelData[] newArray(int size) {return new ParcelData[size];}};}
Note:

1. Parcelable must be implemented.

2. Each variable must have the corresponding Set and Get methods.

3. You need to reload writeToParcel to write data.

4. You must implement Parcelable. Creator <ParcelData> CREATOR, which must be public and static. CreateFromParcel must be reloaded to read data during implementation.

5. TransData must be referenced by TransDataA and TransDataB. To ensure correctness, you can set TransData to Library and then reference it in TransDataA and TransDataB. See



Reprinted, please indicate the source of Android cross-Application Data Transmission


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.