安卓Service向Activity傳遞資料,更新UI
介面回撥、Handler、活動和服務繫結
1服務:執行定時任務,發起網路請求定位,請求到的結果傳遞到活動,在地圖上展示。
2活動關鍵程式碼:
繫結服務後會獲取LocationService.LocationBinder物件,在此處呼叫getLocationService()方法獲取Service例項,service設定回撥介面獲取位置資訊,併發送訊息,handler接收訊息後更新UI。
//繫結服務
private LocationService service;
private ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service=((LocationService.LocationBinder)iBinder).getLocationService();
service.setDataCallback(new LocationService.DataCallback() {
@Override
public void updateui(LocationInfo locationInfo) {
Message message=new Message();
message.what=LocationService.UpdateLocation;
message.obj=locationInfo;
handler.sendMessage(message);
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//handler處理訊息更新UI
public Handler handler=new Handler(){
public void handleMessage(Message message){
switch (message.what){
case LocationService.UpdateLocation:
//更新UI
sLocationInfo=(LocationInfo)message.obj;
baiduMapUtil.showAtLocation(sLocationInfo);
baiduMapUtil.mBaiduMap.clear();
baiduMapUtil.addOverLay(sLocationInfo);
baiduMapUtil.GeoCode(sLocationInfo);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
sLocationInfo.setAddress(address);
baiduMapUtil.showInfoWindow(sLocationInfo);
}
@Override
public void Poi(List<HospitalInfo> list) {
}
});
break;
}
}
};
public class LocationService extends Service {
public static final int UpdateLocation=1;//更新UI
private LocalDB localDB;
private List<People> peoples;
private People mCurrentPeople;
private String mCurrentUserId;
public LocationInfo locationInfo;
private DataCallback dataCallback=null;
public LocationService() {
}
private LocationBinder mBinder=new LocationBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate(){
super.onCreate();
localDB=new LocalDB(this);
peoples=localDB.getMemberList();
mCurrentPeople=peoples.get(0);
mCurrentUserId=mCurrentPeople.getUserid();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
//自定義的非同步定時任務從網路請求定位,獲取經緯度,沒隔10秒請求一次
new MyTask().execute(mCurrentUserId,"0",new Date().getTime()+"");
AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=60*60*1000;
long triggerAtTime= SystemClock.elapsedRealtime()+10*1000;
Intent i=new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,i,0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);
return super.onStartCommand(intent,flags,startId);
}
//定義Binder,獲取服務例項
public class LocationBinder extends Binder {
public LocationService getLocationService(){
return LocationService.this;
}
}
//自定義非同步任務
class MyTask extends AsyncTask<String,Integer,LocationInfo>{
@Override
protected LocationInfo doInBackground(String... params) {
// String userId=params[0];
try {
locationInfo= HttpRequestMethods.getLocation(new PostParameter[]{
new PostParameter("userId", params[0]), new PostParameter("startTime", params[1]),
new PostParameter("endTime", params[2]), new PostParameter("type", "normal")});
} catch (JSONException e) {
e.printStackTrace();
}
return locationInfo;
}
@Override
protected void onPostExecute(LocationInfo locationInfo) {
if(locationInfo!=null){
Log.d("chenmeng9202", locationInfo.getLongitude() + "");
localDB.query("insert or ignore into location_table(user_id,latitude,longitude,time)values(?,?,?,?)",
new String[]{mCurrentUserId, locationInfo.getLatitude() + "", locationInfo.getLongitude() + "", locationInfo.getTime()});
//回撥
dataCallback.updateui(locationInfo);
}
}
}
//設定介面
public void setDataCallback(DataCallback dataCallback){
this.dataCallback=dataCallback;
}
//自定義回撥介面
public interface DataCallback{
void updateui(LocationInfo locationInfo);
}
}
2TripAvtivity完整程式碼
public class TripActivity extends ToolBarActivity implements View.OnClickListener {
private final static String TAG=TripActivity.class.getSimpleName();
private MapView mapView;
private BaiduMapUtil baiduMapUtil;//地圖工具類
private Button btchangeMember;
private Button btDail;
private Button btSearchHospital;
private Button btSearchTrack;
private Button btTripRecord;
private Button btFence;
private static final int SEARCH_TYPE_CITY = 0;
private static final int SEARCH_TYPE_BOUND = 1;
private static final int SEARCH_TYPE_NEARBY = 2;
private List<People> peoples;
private LocalDB localDB;
private String mCurrentUserId;
private People mCurrentPeople;//當前成員
private LocationInfo mLocationInfo;//當前定位資訊
private HospitalInfo hospitalInfo;
private int switch_index;
public Handler handler=new Handler(){
public void handleMessage(Message message){
switch (message.what){
case LocationService.UpdateLocation:
//更新UI
sLocationInfo=(LocationInfo)message.obj;
baiduMapUtil.showAtLocation(sLocationInfo);
baiduMapUtil.mBaiduMap.clear();
baiduMapUtil.addOverLay(sLocationInfo);
baiduMapUtil.GeoCode(sLocationInfo);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
sLocationInfo.setAddress(address);
baiduMapUtil.showInfoWindow(sLocationInfo);
}
@Override
public void Poi(List<HospitalInfo> list) {
}
});
break;
}
}
};
private LocationInfo sLocationInfo;//服務傳回的定位資訊
private LocationService service;
private ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service=((LocationService.LocationBinder)iBinder).getLocationService();
service.setDataCallback(new LocationService.DataCallback() {
@Override
public void updateui(LocationInfo locationInfo) {
Message message=new Message();
message.what=LocationService.UpdateLocation;
message.obj=locationInfo;
handler.sendMessage(message);
}
});
//更新UI
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_trip);
localDB=new LocalDB(this);
peoples=localDB.getMemberList();
initView();
initData();
new LocationTask().execute(mCurrentUserId, "0", new Date().getTime() + "");
Intent bindIntent=new Intent(this,LocationService.class);
startService(bindIntent);
bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
}
private void initData() {
if(peoples!=null&&peoples.size()>0){
mCurrentPeople=peoples.get(0);
mCurrentUserId=peoples.get(0).getUserid();
btchangeMember.setText(peoples.get(0).getUsername());
}
}
private void initView() {
Toolbar toolbar = getToolBar();
((TextView) toolbar.findViewById(R.id.tv_title)).setText("摔倒監護");
btchangeMember=(Button)findViewById(R.id.changeMember);
btchangeMember.setOnClickListener(this);
mapView = (MapView) findViewById(R.id.map_view);
baiduMapUtil=new BaiduMapUtil(getApplicationContext(),mapView);
//底部選單按鈕
btDail=(Button)findViewById(R.id.trip_dail);
btDail.setOnClickListener(this);
btSearchHospital = (Button) findViewById(R.id.search_hospital);
btSearchHospital.setOnClickListener(this);
btSearchTrack = (Button) findViewById(R.id.search_track);
btSearchTrack.setOnClickListener(this);
btTripRecord = (Button) findViewById(R.id.trip_record);
btTripRecord.setOnClickListener(this);
btFence=(Button)findViewById(R.id.trip_fence);
btFence.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
hospitalInfo = (HospitalInfo) b.getSerializable("hospitalInfo");
baiduMapUtil.showAtLocation(hospitalInfo);
baiduMapUtil.addOverLay(hospitalInfo);
baiduMapUtil.GeoCode(hospitalInfo);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
hospitalInfo.setPoiadd(address);
baiduMapUtil.showInfoWindow(hospitalInfo);
}
@Override
public void Poi(List<HospitalInfo> list) {
}
});
baiduMapUtil.setNavigation(new BaiduMapUtil.Navigation() {
@Override
public void navigation(HospitalInfo hospitalInfo) {
Intent intent=new Intent(TripActivity.this,NavigationActivity.class);
intent.putExtra("hospitalinfo",hospitalInfo);
intent.putExtra("lacationinfo",mLocationInfo);
startActivity(intent);
}
});
}
break;
default:
break;
}
}
@Override
protected void onStop() {
super.onStop();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.trip_dail:
String mCurrentPhone= mCurrentPeople.getPhone();
if(mCurrentPhone!=null) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+mCurrentPeople.getPhone()));
TripActivity.this.startActivity(intent);
}else{
ToastShow.ShortToast(getApplicationContext(),"當前成員未繫結手機");
}
break;
case R.id.search_hospital:
LatLng latLng=new LatLng(mLocationInfo.getLatitude(),mLocationInfo.getLongitude());
Log.d("latLng",latLng.latitude+"");
baiduMapUtil.searchByType(SEARCH_TYPE_CITY, latLng);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
}
@Override
public void Poi(List<HospitalInfo> list) {
Log.d("chenmeng","poi");
Intent intent = new Intent(TripActivity.this, HospitalActivity.class);
intent.putExtra("poiResult", (Serializable)list);
startActivityForResult(intent, 1);
}
});
break;
case R.id.search_track:
Intent intenttrack=new Intent(TripActivity.this,TrackActivity.class);
startActivity(intenttrack);
break;
case R.id.trip_record:
Intent intent=new Intent(TripActivity.this,FallRecordActivity.class);
startActivity(intent);
break;
case R.id.trip_fence:
Intent intentfence=new Intent(TripActivity.this,FenceActivity.class);
startActivity(intentfence);
break;
/**
case R.id.bt_map_pattern:
if(mCurrentMode==MyLocationConfiguration.LocationMode.NORMAL){
mCurrentMode= MyLocationConfiguration.LocationMode.FOLLOWING;
btMapPattern.setText("跟隨");
}else{
if( mCurrentMode== MyLocationConfiguration.LocationMode.FOLLOWING) {
mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
btMapPattern.setText("羅盤");
}else {
if(mCurrentMode==MyLocationConfiguration.LocationMode.COMPASS) {
mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
btMapPattern.setText("普通");
}
}
}
break;
**/
case R.id.changeMember: {
final int[] inner_which = {0};
//切換成員
if (peoples != null) {
final String[] name_list = new String[peoples.size()];
final String[] userId_list = new String[peoples.size()];
for (int i = 0; i < peoples.size(); i++) {
name_list[i] = peoples.get(i).getUsername();
userId_list[i] = peoples.get(i).getUserid();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("成員列表");
builder.setSingleChoiceItems(name_list, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch_index = which;
inner_which[0] = which;
}
});
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (inner_which[0] != 0) {
mCurrentPeople=peoples.get(switch_index);
mCurrentUserId = userId_list[switch_index];
btchangeMember.setText(name_list[switch_index]);
}else {
mCurrentPeople=peoples.get(switch_index);
mCurrentUserId = userId_list[0];
btchangeMember.setText(name_list[0]);
}
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
} else {
ToastShow.ShortToast(this, "暫無成員");
}
}
default:
break;
}
}
class LocationTask extends AsyncTask<String,Integer,LocationInfo>{
@Override
protected LocationInfo doInBackground(String... params) {
String userId=params[0];
LocationInfo locationInfo=null;
try {
locationInfo= HttpRequestMethods.getLocation(new PostParameter[]{
new PostParameter("userId",params[0]),new PostParameter("startTime",params[1]),
new PostParameter("endTime",params[2]),new PostParameter("type","normal")});
} catch (JSONException e) {
e.printStackTrace();
}
return locationInfo;
}
@Override
protected void onPostExecute(LocationInfo locationInfo){
mLocationInfo=locationInfo;
baiduMapUtil.showAtLocation(locationInfo);
baiduMapUtil.addOverLay(locationInfo);
baiduMapUtil.GeoCode(locationInfo);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
mLocationInfo.setAddress(address);
baiduMapUtil.showInfoWindow(mLocationInfo);
}
@Override
public void Poi(List<HospitalInfo> list) {
}
});
//存資料庫
localDB.execSQL("insert or ignore into location_table(user_id,latitude,longitude,time) values" +
"(?,?,?,?)",new String[]{mCurrentUserId,locationInfo.getLatitude()+"",locationInfo.getLongitude()+"",locationInfo.getTime()});
}
OnGetGeoCoderResultListener geoListener=new OnGetGeoCoderResultListener() {
@Override
public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
String address = geoCodeResult.getAddress();
LatLng latLng = geoCodeResult.getLocation();
mLocationInfo.setAddress(address);
Log.d(TAG,mLocationInfo.getAddress());
baiduMapUtil.showInfoWindow(mLocationInfo);
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
}
};
}
}
相關推薦
安卓Service向Activity傳遞資料,更新UI
介面回撥、Handler、活動和服務繫結 1服務:執行定時任務,發起網路請求定位,請求到的結果傳遞到活動,在地圖上展示。 2活動關鍵程式碼: 繫結服務後會獲取LocationService.LocationBinder物件,在此處呼叫getLocation
kotlin安卓開發:fragment向activity傳遞資料通過handler,設定回撥方法
從activity向fragment傳遞就比較方便了,直接用: fg.arguments = arguments 現在看看怎麼從fragment向activity傳遞資料。 比如說,我們在一個ViewPage裡面設定了若干個fragment,fragment裡面有一個按鈕,提交相關
flask後端向HTML傳遞資料,用echart生成圖表
用python的flask框架開發一個web,與前端用ajax進行資料互動,反饋至前端後無法生成圖表,請教大神(資料我是開啟的本地的一個Excel中的資料)。程式碼如下:app = Flask(__name__) @app.route('/', methods=['GET'
安卓通過串列埠獲得資料,步驟
1、複製jni資料夾 2、複製lib資料夾 3、複製android_serialport_api 資料夾 4、修改 manifest檔案 <application android:name="android_serialport_api.sample.Appli
Dialog向Activity傳遞資料
本文出處:http://superonion.iteye.com/blog/1418467我們知道,從一個Activity向另一個Activity傳遞資料,用Intent實現。而當一個浮在Activity之上的Dialog需要向該Activity傳遞資料時,應該怎麼實現呢?接著上一篇文章:用Dialog建立帶
3.安卓基礎之Activity間的資料傳遞
零、前言 開啟FromActivity,通過按鈕以返回結果方式開啟ToActivity,同時在intent中加入資料, 在ToActivity的onCreate方法中使用資料填充到TextView上。 按返回按鈕,將ToActivity資料傳遞給FromActi
get是向伺服器獲取資料,而post是向伺服器傳遞資料。到底該怎麼理解
The HTML specifications technically define the difference between "GET" and "POST" so that former means that form data is to be encoded (by a browser) into
安卓Service生命週期,你應該知道的都在這裡
如有轉載,請申明: Service是安卓的四大元件之一。它是一個沒有介面的元件,且優先順序大於後臺程序。 瞭解它的生命週期很有必要。 Service啟動的分類 啟動服務: 通過startService啟動的服務稱為啟動服務 繫結啟動服務: 通過bindSe
安卓APP的儲存目錄+ FileProvider,總結持久化資料的技巧
安卓儲存目錄分為 內部儲存 和 外部儲存。 內部儲存的目錄為 /data/ 目錄, 其中 內部儲存 在未root的手機上是無法檢視的。 要了解APP的儲存目錄結構,我們先從 app開始安裝時談起。 一、apk在安裝時,涉及到目錄
從安卓recovery 的 backup 備份資料中手動恢復 通訊錄、簡訊,或者其他軟體中的資訊的方法
在使用recovery備份後的檔案裡面,一般有一個data.xxx的檔案, 不同的recovery 可能與區別例如data.ext3.tar,用一般的解壓軟體就可以解壓出裡面的檔案,如7z。看到一些文章是將 databases 下的檔案都複製到新系統對應的目錄下,替換到原來的,但我覺得可能對刷了相同系統的有
【Android】安卓開發之activity如何傳值到fragment,activity與fragment傳值
作者:程式設計師小冰,GitHub主頁:https://github.com/QQ986945193 新浪微博:http://weibo.com/mcxiaobing 大家知道,我們利用acti
js和安卓app互相傳資料(安卓app頁面整合html頁面,獲取資料並給安卓返回資料)
先上Demo:<!DOCTYPE html><html><head> <meta charset="utf-8"></head><body><button onclick="test()"&g
Vue2 框架整理:子元件向父元件傳遞資料,$emit() 或 v-on
當子元件向父元件傳遞資料的時候,需要的是自定義事件: $on & $emit 子元件用$emit()觸發事件, 父元件用$on() 監聽子元件的事件 或者父元件也可以直接在子元件的自定義標籤上使用v-on來監聽子元件觸發的自定義事件: $e
Android Service向Activity傳引數和資料
作為Android開發人員來說,Activity 向Service傳資料很容易,用Intent跳轉的時候攜帶資料,但是Service向Activity傳資料對於剛接觸可能相對有點難度,所以,此篇部落格記錄下Service向Activity用廣播傳值。 An
安卓使用Socket發送中文,C語言服務端接收亂碼問題解決方式
article nbsp ons size ret con pre n+1 utf8 今天用安卓通過Socket發送數據到電腦上使用C語言寫的服務端,發送英文沒有問題,可當把數據改變成中文時,服務端接收到的數據確是亂碼。 突然想到。VS的預處理使用的
安卓開發筆記 Activity(四)
nac 創建 intent nbsp star lda this 空白 空白頁 Activity -> Intent -> Activity startActivity(Intent) 創建Activity 步驟: 右擊->new
去除安卓自定義Dialog黑色背景,設置無邊框,透明
isf window bsp 希望 nbsp tle -name rep lan 我們在自定義Dialog的時候,往往會希望除去安卓系統定義背景和標題,以便於更好的顯示我們自己想要的效果。 其實我們只需要註意幾個地方就行了。 1.在Style文件的中定義Dialog的主題
朱雀大廳源碼制作安卓惡意軟件Skygofree爆發,連你的照片都能監控到
進化 收集 工程 一份 全面 惡意軟件 window skype 一個 昨日,根據卡巴斯基實驗室公布的一份報告朱雀大廳源碼制作(h5.hxforum.com)企鵝2952777280 三公,炸金花、三公源碼出售 房卡出售 後臺出租,研究人員發現了一款相當強悍的惡意軟件,名為
Android 中Application向Activity 傳遞數值
指定 實現 clas Nid OS roi IT 如何獲取 傳遞 比如極光註冊時獲取用戶的唯一標示ID需要在登錄時進行傳遞,實現消息的指定用戶推送功能 1 public String id; 2 3 public String getId() { 4
安卓中管理Activity
安卓中一般在BaseActivity 管理所有的Activity 因為所有的Activity 繼承自BaseActivity 步驟: 1:在BaseActivity New 一個ArrayList 儲存Activity private List<Activity> allA