最近在学习做个小demo,需要用到Service与Activity交互,经过上网和看书了解可以利用广播也就是 BroadcastReceive让Service与Activity交互数据。
这里我就是用GPS定位的demo举例。
</pre></p><pre name="code" class="java">public class MainActivity extends Activity {
private TextView LatitudeView;
private TextView LongitudeView;
private Button button;
private Boolean blnGo = false;
<span style="font-family: Arial, Helvetica, sans-serif;"> ServiceReceiver serviceReceiver;</span>
private int CMD_START_LOCATION = 1;
private int CMD_STOP_LOCATION = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//这里初始化TextView和|Button.
LatitudeView = (TextView)findViewById(R.id.Latitude);
LongitudeView = (TextView)findViewById(R.id.Longitude);
button =(Button)findViewById(R.id.button);
//当Activity创建时就启动Service.
Intent intent = new Intent(MainActivity.this, Service_activity.class);
MainActivity.this.startService(intent);
//button的 监听器
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
LongitudeView.setText("0");
LatitudeView.setText("0");
if (!blnGo) {
button.setText("Stop");
blnGo = true;
//设置Intent的属性,同时把到从Activity要发送的到Service的消息放进putExtra()方法中
Intent intent = new Intent();
//这里的设置Intent的Action属性一定要跟Service中注册注册广播时filter的addAction一样
intent.setAction("from Activity");
intent.putExtra("cmd", CMD_START_LOCATION);
//发送开始定位的广播,
sendBroadcast(intent);
System.out.println("Activity---->CMD_START_LOCATION");
} else {
button.setText("Start");
blnGo = false;
Intent intent = new Intent();
intent.setAction("from Activity");
//发送停止定位的广播
intent.putExtra("cmd", CMD_STOP_LOCATION);
sendBroadcast(intent);
System.out.println("Activity---->CMD_STOP_LOCATION");
}
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
// TODO Auto-generated method stub
serviceReceiver = new ServiceReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("from Service");
//注册广播监听
registerReceiver(serviceReceiver, filter);
super.onStart();
}
@Override
protected void onDestroy() {
//解除广播监听
// TODO Auto-generated method stub
unregisterReceiver(serviceReceiver);
finish();
super.onDestroy();
}
//广播接收器,接收从Service发送回来的经纬度信息
private class ServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//从intent中取数据
double lat = intent.getDoubleExtra("lat", 0.1);
LatitudeView.setText(String.valueOf(lat));
double lng = intent.getDoubleExtra("lng", 0.2);
LongitudeView.setText(String.valueOf(lng));
System.out.println("-----Activity-onRecevice------");
System.out.println("Activity--->lat(纬度)" + lat);
System.out.println("Activity--->lng(经度)" + lng);
}
}
}
//Service类
public class Service_activity extends Service{
private LocationManager locationManager;
private int CMD_START_LOCATION = 1;
private int CMD_STOP_LOCATION = 0;
ActivityRecevice activityRecevice;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//当Service开始时,开始接收从Activity发送回来的信息
ctivityRecevice = new ActivityRecevice();
IntentFilter filter = new IntentFilter();
//这里addAction("")的设置和Activity中要发送消息的Intent设置的setAction()一样
filter.addAction("from Activity");
registerReceiver(activityRecevice, filter);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(activityRecevice);
super.onDestroy();
}
//当接收到Activity发来的信息所要做的事情,开始定位或结束定位
private class ActivityRecevice extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int cmd = intent.getIntExtra("cmd", -1);
if (cmd == CMD_START_LOCATION) {
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER
, 2000, (float) 1.5, locationListener);
Location location =locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Intent dataintent = new Intent();
//同样这里设置的setAction和Activity注册广播监听时filter的addAction()要一样
dataintent.setAction("from Service");
dataintent.putExtra("lat", lat);
dataintent.putExtra("lng", lng);
sendBroadcast(dataintent);
System.out.println("cmd == CMD_START_LOCATION");
System.out.println("Service1----->lat = " + lat);
System.out.println("Service1----->lng = " + lng);
}
}
if (cmd == CMD_STOP_LOCATION) {
//当Activity发送停止定位时移除定位监听
locationManager.removeUpdates(locationListener);
System.out.println("cmd == CMD_STOP_LOCATION");
}
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
UpdateView(locationManager.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
UpdateView(null);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
UpdateView(location);
}
<span style="white-space:pre"> </span>private void UpdateView(Location location) {
<span style="white-space:pre"> </span>if (location != null) {
<span style="white-space:pre"> </span>double lat = location.getLatitude();
<span style="white-space:pre"> </span>double lng = location.getLongitude();
<span style="white-space:pre"> </span>Intent dataintent = new Intent();
<span style="white-space:pre"> </span>dataintent.setAction("from Service");
<span style="white-space:pre"> </span>dataintent.putExtra("lat", lat);
<span style="white-space:pre"> </span>dataintent.putExtra("lng", lng);
<span style="white-space:pre"> </span>sendBroadcast(dataintent);
<span style="white-space:pre"> </span>System.out.println("------UpdateView-------");
<span style="white-space:pre"> </span>System.out.println("Service2----->lat = " + lat);
<span style="white-space:pre"> </span>System.out.println("Service2----->lng = " + lng);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
};
}
</pre><pre name="code" class="java">
public class MainActivity extends Activity {
private TextView LatitudeView;
private TextView LongitudeView;
private Button button;
private Boolean blnGo = false;
<span style="font-family: Arial, Helvetica, sans-serif;"> ServiceReceiver serviceReceiver;</span>
private int CMD_START_LOCATION = 1;
private int CMD_STOP_LOCATION = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//这里初始化TextView和|Button.
LatitudeView = (TextView)findViewById(R.id.Latitude);
LongitudeView = (TextView)findViewById(R.id.Longitude);
button =(Button)findViewById(R.id.button);
//当Activity创建时就启动Service.
Intent intent = new Intent(MainActivity.this, Service_activity.class);
MainActivity.this.startService(intent);
//button的 监听器
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
LongitudeView.setText("0");
LatitudeView.setText("0");
if (!blnGo) {
button.setText("Stop");
blnGo = true;
//设置Intent的属性,同时把到从Activity要发送的到Service的消息放进putExtra()方法中
Intent intent = new Intent();
//这里的设置Intent的Action属性一定要跟Service中注册注册广播时filter的addAction一样
intent.setAction("from Activity");
intent.putExtra("cmd", CMD_START_LOCATION);
//发送开始定位的广播,
sendBroadcast(intent);
System.out.println("Activity---->CMD_START_LOCATION");
} else {
button.setText("Start");
blnGo = false;
Intent intent = new Intent();
intent.setAction("from Activity");
//发送停止定位的广播
intent.putExtra("cmd", CMD_STOP_LOCATION);
sendBroadcast(intent);
System.out.println("Activity---->CMD_STOP_LOCATION");
}
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
// TODO Auto-generated method stub
serviceReceiver = new ServiceReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("from Service");
//注册广播监听
registerReceiver(serviceReceiver, filter);
super.onStart();
}
@Override
protected void onDestroy() {
//解除广播监听
// TODO Auto-generated method stub
unregisterReceiver(serviceReceiver);
finish();
super.onDestroy();
}
//广播接收器,接收从Service发送回来的经纬度信息
private class ServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//从intent中取数据
double lat = intent.getDoubleExtra("lat", 0.1);
LatitudeView.setText(String.valueOf(lat));
double lng = intent.getDoubleExtra("lng", 0.2);
LongitudeView.setText(String.valueOf(lng));
System.out.println("-----Activity-onRecevice------");
System.out.println("Activity--->lat(纬度)" + lat);
System.out.println("Activity--->lng(经度)" + lng);
}
}
}
//Service类
public class Service_activity extends Service{
private LocationManager locationManager;
private int CMD_START_LOCATION = 1;
private int CMD_STOP_LOCATION = 0;
ActivityRecevice activityRecevice;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//当Service开始时,开始接收从Activity发送回来的信息
ctivityRecevice = new ActivityRecevice();
IntentFilter filter = new IntentFilter();
//这里addAction("")的设置和Activity中要发送消息的Intent设置的setAction()一样
filter.addAction("from Activity");
registerReceiver(activityRecevice, filter);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(activityRecevice);
super.onDestroy();
}
//当接收到Activity发来的信息所要做的事情,开始定位或结束定位
private class ActivityRecevice extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int cmd = intent.getIntExtra("cmd", -1);
if (cmd == CMD_START_LOCATION) {
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER
, 2000, (float) 1.5, locationListener);
Location location =locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Intent dataintent = new Intent();
//同样这里设置的setAction和Activity注册广播监听时filter的addAction()要一样
dataintent.setAction("from Service");
dataintent.putExtra("lat", lat);
dataintent.putExtra("lng", lng);
sendBroadcast(dataintent);
System.out.println("cmd == CMD_START_LOCATION");
System.out.println("Service1----->lat = " + lat);
System.out.println("Service1----->lng = " + lng);
}
}
if (cmd == CMD_STOP_LOCATION) {
//当Activity发送停止定位时移除定位监听
locationManager.removeUpdates(locationListener);
System.out.println("cmd == CMD_STOP_LOCATION");
}
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
UpdateView(locationManager.getLastKnownLocation(provider));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
UpdateView(null);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
UpdateView(location);
}
private void UpdateView(Location location) {
// TODO Auto-generated method stub
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Intent dataintent = new Intent();
dataintent.setAction("from Service");
dataintent.putExtra("lat", lat);
dataintent.putExtra("lng", lng);
sendBroadcast(dataintent);
System.out.println("------UpdateView-------");
System.out.println("Service2----->lat = " + lat);
System.out.println("Service2----->lng = " + lng);
}
}
};
}