BroadcastReceiver Android
Demo send & get data between 2 application via BroadcastReceiver
First App
Manifest
<receiver android:name="MyReceiver"> <intent-filter> <action android:name="com.android.abc.demo"> </action> </intent-filter> </receiver>
public class MyReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Start send data...", Toast.LENGTH_SHORT).show(); Intent i = new Intent(); i.setAction("android.intent.action.demo"); i.putExtra("user", "userName"); i.putExtra("pass", "PassWord"); context.sendBroadcast(i); } }
Second App
public class MainActivity extends AppCompatActivity { private BroadcastReceiver ReceivefromService = new BroadcastReceiver() { @Override
public void onReceive(Context context, Intent intent) { //get the data using the keys you entered at the service
Toast.makeText(context,intent.getAction(),Toast.LENGTH_SHORT).show(); String user = intent.getStringExtra("user");//
String pass = intent.getStringExtra("pass"); tvGetdata.setText(user + "\n" + pass); } }; TextView tvGetdata; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvGetdata = (TextView) findViewById(R.id.tvGetdata); button=(Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View view) { Intent intent = new Intent(); intent.setAction("com.android.abc.demo"); sendBroadcast(intent); } }); IntentFilter in = new IntentFilter(); in.addAction("android.intent.action.demo"); registerReceiver(ReceivefromService,in); } }
No comments:
Post a Comment