service和activity通信
Activity:Intent serviceIntent = new Intent(this,ListenLocationService.class);
serviceIntent.putExtra("From", "Main");
startService(serviceIntent);
//and get the parameter in onStart method of your service class
service:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Bundle extras = intent.getExtras();
if(extras == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
String from = (String) extras.get("From");
if(from.equalsIgnoreCase("Main"))
StartListenLocation();
}
如果putExtra输入是Int, 在bundle就要用getInt 类型一定要match 否则报错!
Fragment和Activity通信:
Fragment->Activity:In your fragment you can call getActivity(). This will give you access to the activity that created the fragment. From there you can obviously call any sort of accessor methods that are in the activity.
MainFragmentActivity parent;
parent.setCurrentLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
setCurrentLatLng是activity的方法
Activity和Activity通信:
基本类型:Activity 1:
Intent intent = new Intent(getActivity() ,PathDetailActivity.class);
int pathid=pos;
intent.putExtra("pathid", pathid);
getActivity().startActivity(intent);
Activity 2
Intent intent = getIntent();
int pathid = intent.getIntExtra("pathid", 0);
复合类型:
Activity 1:
Intent intent = new Intent(getActivity() ,PathDetailActivity.class);
Bundle data = new Bundle(); data.putParcelable("stats", stats.get(pos));
intent.putExtra("bundle",data); getActivity().
startActivity(intent);
Activity 2
Intent intent = getIntent();
Bundle bundle = intent.getParcelableExtra("bundle");
Stats stats = bundle.getParcelable("stats");
这里Stats必须是实现Parcelable
http://techdroid.kbeanie.com/2010/06/parcelable-how-to-do-that-in-android.html
Activity 1:
Bundle data = new Bundle();
Intent intent = new Intent(MainFragmentActivity.this,CheckinActivity.class);
//intent.putExtra("pathid", pathid);
data.putParcelable("currentPoint", this.curPoint);
data.putInt("pathid", pathid);
intent.putExtra("bundle",data);
startActivity(intent);
利用intent通信,数据可以是基本类型(pathid is int),也可以是复合甚至自定义类型,可以用bundle封装 curPoint是LatLng类型.
Activity 2(onCreate):
Intent intent = getIntent();
//pathid = intent.getIntExtra("pathid", 0);
Bundle bundle = intent.getParcelableExtra("bundle");
curPoint = bundle.getParcelable("currentPoint");
pathid = bundle.getInt("pathid");
当然也可以用data.putSerializable("person",p)来封装,具体见android讲义P240
No comments:
Post a Comment