1. 程式人生 > >Glide快取圖片清除快取,百度地圖定位

Glide快取圖片清除快取,百度地圖定位

1.匯入百度地圖jar包與jniLibs檔案,獲取到appId

2.清單檔案

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baway.yuekao6">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name=
"android.permission.INTERNET"/> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /> <uses-permission android:name="android.permission.WAKE_LOCK"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="qp6lXouqtI3gtxohcqcaqY4dGxfaOlYA" /> <activity android:name=".activity.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote"> </service> </application> </manifest>
3.activity_main佈局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
    <com.liaoinstan.springview.widget.SpringView
android:id="@+id/springView"
android:layout_width="match_parent"
android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
    </com.liaoinstan.springview.widget.SpringView>
    <LinearLayout
android:id="@+id/li_location"
android:layout_width="100dp"
android:layout_height="80dp"
android:orientation="vertical"
android:background="#ffffff">
        <TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:text="定位"
android:gravity="center_vertical"/>
        <TextView
android:id="@+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:text="sssss"
android:gravity="center_vertical"/>
    </LinearLayout>
    <LinearLayout
android:id="@+id/li_cache"
android:layout_width="100dp"
android:layout_height="80dp"
android:orientation="vertical"
android:layout_alignParentRight="true"
android:background="#ffffff">
        <TextView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:text="清除快取"
android:gravity="center_vertical"/>
        <TextView
android:id="@+id/tv_cache"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginLeft="20dp"
android:text="sssss"
android:gravity="center_vertical"/>
    </LinearLayout>
    <com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:visibility="gone"/>
</RelativeLayout>
4.recyclerView條目佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="500dp">
    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="400dp">
        <ImageView
android:id="@+id/item_iv"
android:layout_width="match_parent"
android:layout_height="400dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"/>
        <TextView
android:id="@+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:text="sssssss"/>
    </RelativeLayout>
    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp">
        <TextView
android:id="@+id/item_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="26"
android:padding="5dp"
android:gravity="center"
android:background="#94D3D6"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"/>
        <TextView
android:id="@+id/item_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="銀行"
android:padding="5dp"
android:gravity="center"
android:background="#EFBE42"
android:layout_centerVertical="true"
android:layout_marginLeft="100dp"/>
    </RelativeLayout>
    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp">
        <TextView
android:id="@+id/item_introduction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
android:layout_centerVertical="true"/>
    </RelativeLayout>
</LinearLayout>
5.MainActivity程式碼
public class MainActivity extends AppCompatActivity {

    private SpringView springView;
    private RecyclerView recycler;
    private LinearLayout li_cache;
    private LinearLayout li_location;
    private TextView tv_cache;
    private TextView tv_location;
    private int page=1;
    private List<DataBean.Data> data;
    private MyAdapter adapter;
    private MapView bmapView;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener();
    private boolean isFirstLoc = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
initView();
getServerData();
}

    private void getServerData() {
        String url="http://www.yulin520.com/a2a/impressApi/news/mergeList?sign=C7548DE604BCB8A17592EFB9006F9265&pageSize=10&gender=2&ts=1871746850&page="+page;
MyAsyncTask task=new MyAsyncTask();
task.execute(url);
}

    private void initView() {
        springView = (SpringView) findViewById(R.id.springView);
recycler = (RecyclerView) findViewById(R.id.recycler);
li_cache = (LinearLayout) findViewById(R.id.li_cache);
li_location = (LinearLayout) findViewById(R.id.li_location);
tv_cache = (TextView) findViewById(R.id.tv_cache);
tv_location = (TextView) findViewById(R.id.tv_location);
bmapView = (MapView) findViewById(R.id.bmapView);
springView.setType(SpringView.Type.FOLLOW);
springView.setHeader(new DefaultHeader(this));
springView.setFooter(new DefaultFooter(this));
springView.setListener(new SpringView.OnFreshListener() {
            @Override
public void onRefresh() {
                page=1;
getServerData();
                new Handler().postDelayed(new Runnable() {
                    @Override
public void run() {
                        springView.onFinishFreshAndLoad();
}
                },2000);
}

            @Override
public void onLoadmore() {
                page++;
getServerData();
                new Handler().postDelayed(new Runnable() {
                    @Override
public void run() {
                        springView.onFinishFreshAndLoad();
}
                },2000);
}
        });
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
recycler.setLayoutManager(layoutManager);
recycler.addItemDecoration(new RecycleViewDivider(this,LinearLayoutManager.HORIZONTAL,R.drawable.divider));
recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
tv_cache.setText(GlideCacheUtil.getInstance().getCacheSize(MainActivity.this));
}
        });
li_cache.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                GlideCacheUtil.getInstance().clearImageAllCache(MainActivity.this);
tv_cache.setText(GlideCacheUtil.getInstance().getCacheSize(MainActivity.this));
}
        });
li_location.setOnClickListener(new View.OnClickListener() {
            @Override
public void onClick(View v) {
                //獲取地圖
baiduMap = bmapView.getMap();
//開啟定點陣圖層
baiduMap.setMyLocationEnabled(true);
tv_location = (TextView) findViewById(R.id.tv_location);
//初始化定位物件  宣告LocationClientmLocationClient = new LocationClient(getApplicationContext());
//註冊監聽函式
mLocationClient.registerLocationListener(myListener);
initLocation();
                int checkPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
Log.d("TTTT", "彈出提示");
                    return;
} else {
                    //開啟定位
mLocationClient.start();
}
            }
        });
}
    class MyAsyncTask extends AsyncTask<String,Integer,String>{

        @Override
protected String doInBackground(String... params) {
            return MyOkhttp.get(params[0]);
}

        @Override
protected void onPostExecute(String s) {
            super.onPostExecute(s);
String json=s.toString();
Gson gson=new Gson();
DataBean dataBean = gson.fromJson(json, DataBean.class);
            if (data==null) {
                data = dataBean.data;
}else{
                data.addAll(dataBean.data);
}
            initAdapter();
}
    }

    private void initAdapter() {
        if (adapter==null) {
            adapter = new MyAdapter(this, data);
recycler.setAdapter(adapter);
}else{
            adapter.notifyDataSetChanged();
}
    }
    @Override
protected void onDestroy() {
        super.onDestroy();
//activity執行onDestroy時執行mMapView.onDestroy(),實現地圖生命週期管理
bmapView.onDestroy();
}
    @Override
protected void onResume() {
        super.onResume();
//activity執行onResume時執行mMapView. onResume (),實現地圖生命週期管理
bmapView.onResume();
}
    @Override
protected void onPause() {
        super.onPause();
//activity執行onPause時執行mMapView. onPause (),實現地圖生命週期管理
bmapView.onPause();
}
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可選,預設高精度,設定定位模式,高精度,低功耗,僅裝置
option.setCoorType("bd09ll");
//可選,預設gcj02,設定返回的定位結果座標系
int span = 1000;
option.setScanSpan(span);
//可選,預設0,即僅定位一次,設定發起定位請求的間隔需要大於等於1000ms才是有效的
option.setIsNeedAddress(true);
//可選,設定是否需要地址資訊,預設不需要
option.setOpenGps(true);
//可選,預設false,設定是否使用gps
option.setLocationNotify(true);
//可選,預設false,設定是否當GPS有效時按照1S/1次頻率輸出GPS結果
option.setIsNeedLocationDescribe(true);
//可選,預設false,設定是否需要位置語義化結果,可以在BDLocation.getLocationDescribe裡得到,結果類似於在北京天安門附近option.setIsNeedLocationPoiList(true);
//可選,預設false,設定是否需要POI結果,可以在BDLocation.getPoiList裡得到
option.setIgnoreKillProcess(false);
//可選,預設true,定位SDK內部是一個SERVICE,並放到了獨立程序,設定是否在stop的時候殺死這個程序,預設不殺死
option.SetIgnoreCacheException(false);
//可選,預設false,設定是否收集CRASH資訊,預設收集
option.setEnableSimulateGps(false);
//可選,預設false,設定是否需要過濾GPS模擬結果,預設需要
mLocationClient.setLocOption(option);
}

    public class MyLocationListener implements BDLocationListener {

        @Override
public void onReceiveLocation(BDLocation location) {

            //獲取定位結果
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());    //獲取定位時間
sb.append("\nerror code : ");
sb.append(location.getLocType());    //獲取型別型別
sb.append("\nlatitude : ");
sb.append(location.getLatitude());    //獲取緯度資訊
sb.append("\nlontitude : ");
sb.append(location.getLongitude());    //獲取經度資訊
sb.append("\nradius : ");
sb.append(location.getRadius());    //獲取定位精準度
//---------------------將地圖跟定位關聯起來----------------------------------------
MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此處設定開發者獲取到的方向資訊,順時針0-360
.direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
// 設定定位資料
baiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatus.Builder builder = new MapStatus.Builder();
builder.target(ll).zoom(18.0f);
baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
}
//---------------------將地圖跟定位關聯起來----------------------------------------
if (location.getLocType() == BDLocation.TypeGpsLocation) {

                // GPS定位結果
sb.append("\nspeed : ");
sb.append(location.getSpeed());    // 單位:公里每小時
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());    //獲取衛星數
sb.append("\nheight : ");
sb.append(location.getAltitude());    //獲取海拔高度資訊,單位米
sb.append("\ndirection : ");
sb.append(location.getDirection());    //獲取方向資訊,單位度
sb.append("\naddr : ");
sb.append(location.getAddrStr());    //獲取地址資訊
sb.append("\ndescribe : ");
sb.append("gps定位成功");
}  else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                // 網路定位結果
sb.append("\naddr : ");
sb.append(location.getAddrStr());    //獲取地址資訊
sb.append("\noperationers : ");
sb.append(location.getOperators());    //獲取運營商資訊
sb.append("\ndescribe : ");
sb.append("網路定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 離線定位結果
sb.append("\ndescribe : ");
sb.append("離線定位成功,離線定位結果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {

                sb.append("\ndescribe : ");
sb.append("服務端網路定位失敗,可以反饋IMEI號和大體定位時間到[email protected],會有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                sb.append("\ndescribe : ");
sb.append("網路不同導致定位失敗,請檢查網路是否通暢");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                sb.append("\ndescribe : ");
sb.append("無法獲取有效定位依據導致定位失敗,一般是由於手機的原因,處於飛航模式下一般會造成這種結果,可以試著重啟手機");
}

            sb.append("\nlocationdescribe : ");
sb.append(location.getLocationDescribe());    //位置語義化資訊
final List<Poi> list = location.getPoiList();    // POI資料
if (list != null) {
                sb.append("\npoilist size = : ");
sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
}

            }
            //此方法執行在子執行緒
runOnUiThread(new Runnable() {
                @Override
public void run() {
                    tv_location.setText(list.get(2).getName());
}
            });
Log.i("BaiduLocationApiDem", sb.toString() + ",目前位置:" + list.get(2).getName());
}

        @Override
public void onConnectHotSpotMessage(String s, int i) {

        }
    }
}
6.recyclerView介面卡
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
    private Context context;
    private List<DataBean.Data> data;
    public MyAdapter(Context context, List<DataBean.Data> data) {
        this.context = context;
        this.data = data;
}

    @Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=View.inflate(context, R.layout.recycler_item,null);
        return new MyViewHolder(view);
}

    @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
        Glide.with(context).load(data.get(position).img).into(holder.item_iv);
String[] split = data.get(position).title.split(":");
holder.item_name.setText(split[0]);
holder.item_age.setText(data.get(position).userAge+"");
holder.item_job.setText(data.get(position).occupation);
holder.item_introduction.setText(data.get(position).introduction);
}

    @Override
public int getItemCount() {
        return data.size();
}

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        private final ImageView item_iv;
        private final TextView