GPS、藍芽、解析字串等功能
阿新 • • 發佈:2018-11-04
主體佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:onClick="click" android:text="跳轉到GPS" android:id="@+id/btn_gps" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:onClick="click" android:text="跳轉到藍芽" android:id="@+id/btn_bluetooth" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <android.support.v7.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView> </LinearLayout>
GPS佈局
<?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:id="@+id/activity_gps" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".GpsActivity"> <EditText android:id="@+id/et_gps" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:text="返回" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:id="@+id/btn_back" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
藍芽佈局
<?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:id="@+id/activity_bluetooth" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <TextView android:id="@+id/searchBlueTooth" android:text="點選搜尋藍芽" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/devices_list" android:visibility="gone" android:layout_below="@+id/searchBlueTooth" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ListView android:id="@+id/bluetooth_devices_list" android:layout_below="@+id/searchBlueTooth" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ListView> </RelativeLayout>
devices_list佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/devices_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
list_item佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
recyclr_layout佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
主體程式碼
package com.example.mydemo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.google.gson.Gson;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recycler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void parseJson(String json) {
Gson gson = new Gson();
Food food = gson.fromJson(json, Food.class);
List<Food.DataBean> list = new ArrayList<>();
for (int i = 0; i < food.getData().size(); i++) {
list.add(food.getData().get(i));
}
addRecycler(list);
addDataBase(list);
}
//資料來源與RecyclerView繫結
private void addRecycler(List<Food.DataBean> list) {
MyRecyclerAdapter adapter = new MyRecyclerAdapter(list, this);
recycler.setAdapter(adapter);
}
//將從網路上獲取的資料新增到資料庫中
private void addDataBase(List<Food.DataBean> list) {
MySQliteOpenHelper mySQLiteDataBase = new MySQliteOpenHelper(this);
SQLiteDatabase database = mySQLiteDataBase.getWritableDatabase();
for (int i = 0; i < list.size(); i++) {
ContentValues values = new ContentValues();
values.put("pic", list.get(i).getPic());
values.put("title", list.get(i).getTitle());
database.insert("data", null, values);
}
}
//從網路上獲取資料並解析
private void getData() {
String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
RequestParams requestParams = new RequestParams(path);
x.http().get(requestParams, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
parseJson(result);//解析資料
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
}
public void click(View view) {
switch (view.getId()) {
case R.id.btn_gps:
startActivity(new Intent(this, GpsActivity.class));//跳轉到GPS頁面
break;
case R.id.btn_bluetooth:
startActivity(new Intent(this,BluetoothActivity.class));//跳轉到藍芽頁面
break;
}
}
private void initView() {
recycler = (RecyclerView) findViewById(R.id.recycler);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recycler.setLayoutManager(manager);
getData();
}
}
食物程式碼
package com.example.mydemo;
import java.util.List;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
public class Food {
/**
* ret : 1
* data : [{"id":"8289","title":"油燜大蝦","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg","collect_num":"1646","food_str":"大蝦 蔥 生薑 植物油 料酒","num":1646},{"id":"2127","title":"四川回鍋肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg","collect_num":"1580","food_str":"豬肉 青蒜 青椒 紅椒 薑片","num":1580},{"id":"30630","title":"超簡單芒果布丁","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg","collect_num":"1514","food_str":"QQ糖 牛奶 芒果","num":1514},{"id":"9073","title":"家常紅燒魚","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg","collect_num":"1416","food_str":"鮮魚 姜 蔥 蒜 花椒","num":1416},{"id":"10097","title":"家常煎豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg","collect_num":"1399","food_str":"豆腐 新鮮紅椒 青椒 蔥花 油","num":1399},{"id":"10509","title":"水煮肉片","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10509.jpg","collect_num":"1334","food_str":"瘦豬肉 生菜 豆瓣醬 幹辣椒 花椒","num":1334},{"id":"46968","title":"紅糖蘋果銀耳湯","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/47/46968.jpg","collect_num":"1240","food_str":"銀耳 蘋果 紅糖","num":1240},{"id":"10191","title":"麻婆豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10191.jpg","collect_num":"1208","food_str":"豆腐 肉末 生抽 白糖 芝麻油","num":1208},{"id":"2372","title":"皮蛋瘦肉粥","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2372.jpg","collect_num":"1138","food_str":"大米 皮蛋 豬肉 油條 香蔥","num":1138},{"id":"2166","title":"螞蟻上樹","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2166.jpg","collect_num":"1134","food_str":"紅薯粉 肉 姜 蒜 花椒","num":1134},{"id":"2262","title":"糖醋肉","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2262.jpg","collect_num":"1069","food_str":"豬肉 紅椒 黃椒 洋蔥 蛋清","num":1069},{"id":"9971","title":"魚香豆腐","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9971.jpg","collect_num":"1001","food_str":"豆腐 木耳 胡蘿蔔 香蔥 番茄醬","num":1001},{"id":"10172","title":"乾煸四季豆","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10172.jpg","collect_num":"986","food_str":"四季豆 幹辣椒 蒜頭 醬油 糖","num":986},{"id":"2685","title":"胡蘿蔔肉末蒸蛋","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2685.jpg","collect_num":"905","food_str":"胡蘿蔔 肉 蛋 生抽 鹽","num":905},{"id":"9972","title":"虎皮青椒","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9972.jpg","collect_num":"885","food_str":"青辣椒 大蒜 香醋 白糖 生抽","num":885},{"id":"10437","title":"叉燒排骨","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10437.jpg","collect_num":"792","food_str":"排骨 李錦記叉燒醬 植物油 清水 油菜","num":792},{"id":"2892","title":"\u201c五行\u201d彩蔬湯","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2892.jpg","collect_num":"755","food_str":"黑木耳 玉米 牛蒡 胡蘿蔔 西蘭花","num":755},{"id":"2348","title":"麻辣肉絲麵","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2348.jpg","collect_num":"751","food_str":"麵條 肉絲 澱粉 醬油 辣椒","num":751},{"id":"33783","title":"美人豆漿","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/34/33783.jpg","collect_num":"750","food_str":"黃豆 紅豆 綠豆 黑豆 黑米","num":750},{"id":"10044","title":"土豆燉翅根","pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10044.jpg","collect_num":"749","food_str":"土豆 翅根 蔥 姜 料酒","num":749}]
*/
private int ret;
private List<DataBean> data;
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
/**
* id : 8289
* title : 油燜大蝦
* pic : http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg
* collect_num : 1646
* food_str : 大蝦 蔥 生薑 植物油 料酒
* num : 1646
*/
private String id;
private String title;
private String pic;
private String collect_num;
private String food_str;
private int num;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getCollect_num() {
return collect_num;
}
public void setCollect_num(String collect_num) {
this.collect_num = collect_num;
}
public String getFood_str() {
return food_str;
}
public void setFood_str(String food_str) {
this.food_str = food_str;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
}
藍芽程式碼
package com.example.mydemo;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
public class BluetoothActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = "ABCDE";
private List<String> dataSource = new ArrayList<>();
private TextView devices_list;
private BluetoothAdapter bluetoothAdapter;
private Set<BluetoothDevice> bondedDevices;
private TextView searchBlueTooth;
private ListView bluetooth_devices_list;
//第二部開啟廣播並且進行獲取周邊藍芽並輸出到TextView
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
bluetoothAdapter.isEnabled();
String action = intent.getAction();
//獲取已經搜尋到的裝置
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (/*bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED*/true) {
String address = bluetoothDevice.getAddress();//獲取藍芽的MAC地址
String name = bluetoothDevice.getName();//獲取藍芽的名稱
String name_address= name + ":" + address;
dataSource.add(name_address);
// devices_list.append(name + ":" + address + "\n");//將藍芽的地址和名稱設定到TextView上
}
} else if (bluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
devices_list.append("搜尋完畢");
MyListViewAdapter myListViewAdapter = new MyListViewAdapter(BluetoothActivity.this,dataSource);
bluetooth_devices_list.setAdapter(myListViewAdapter);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//啟動子執行緒建立藍芽伺服器
IntentFilter intentFilter = new IntentFilter();//廣播接收者的過濾器
intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);//新增
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);//添加發現藍芽裝置的action動作
intentFilter.addAction(bluetoothAdapter.ACTION_DISCOVERY_FINISHED);//掃描藍芽裝置完畢
this.registerReceiver(receiver, intentFilter);//註冊藍芽廣播
//第一步開啟藍芽並且將獲取到的資訊輸出
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//獲取藍芽介面卡
bondedDevices = bluetoothAdapter.getBondedDevices();//將搜尋到的藍芽裝置放入Set集合中
/* for (BluetoothDevice device : bondedDevices) {
String address = device.getAddress();//獲取藍芽的MAC地址
String name = device.getName();//獲取藍芽的名稱
devices_list.append(name + ":" + address + "\n");//將藍芽的地址和名稱設定到TextView上
}*/
BluetoothServerSocketThread bluetoothServerSocketThread = new BluetoothServerSocketThread();
bluetoothServerSocketThread.start();//開啟子執行緒
}
//第三部進行例項化
private void initView() {
devices_list = (TextView) findViewById(R.id.devices_list);
searchBlueTooth = (TextView) findViewById(R.id.searchBlueTooth);
searchBlueTooth.setOnClickListener(this);
bluetooth_devices_list = (ListView) findViewById(R.id.bluetooth_devices_list);
//為ListView新增點選事件,事件的具體內容上是建立藍芽客戶端,客戶端給伺服器傳送一條訊息
bluetooth_devices_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String TAG = "ABCDE";
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG,"0");
String devices_name_addresss = dataSource.get(position);//從掃描到的藍芽裝置中拿到藍芽裝置的地址和名稱
Log.i(TAG,"1");
// bw:11.22222.444
String devices_addresss = devices_name_addresss.substring(devices_name_addresss.indexOf(":") + 1);
Log.i(TAG,"2");
//getRemoteDevice(String address)
//通過藍芽裝置的地址建立藍芽裝置
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices_addresss);
Log.i(TAG,"3");
// createRfcommSocketToServiceRecord(UUID uuid)
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Log.i(TAG,"4");
try {
//根據已經建立的藍芽裝置建立一個該藍芽裝置的客戶端,這裡的uuid相當於是一個IP地址,通過地址就可以找到伺服器
BluetoothSocket devicesClient = remoteDevice.createRfcommSocketToServiceRecord(uuid);
Log.i(TAG,"5");
devicesClient.connect();//連結到藍芽伺服器
Log.i(TAG,"6");
OutputStream outputStream = devicesClient.getOutputStream();
Log.i(TAG,"7");
outputStream.write("傳送資訊到藍芽裝置".getBytes());
Log.i(TAG,"8");
outputStream.flush();
Log.i(TAG,"9");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
//點選搜尋周圍的藍芽
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchBlueTooth://點選按鈕開始搜尋周邊的藍芽
if (bluetoothAdapter.isDiscovering()) {//如果正在搜尋藍芽就停止搜尋
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();//使用藍芽介面卡搜尋周邊藍芽
break;
}
}
//自定義一個展示發現的藍芽裝置的LListView控制元件的介面卡
class MyListViewAdapter extends BaseAdapter {
private Context context;
private List<String> dataSource ;
public MyListViewAdapter(Context context, List<String> dataSource) {
this.context = context;
this.dataSource = dataSource;
}
@Override
public int getCount() {//獲取item條目的個數
return dataSource.size();
}
@Override
public Object getItem(int position) {
return dataSource.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_item, null);
}
TextView item = (TextView) convertView.findViewById(R.id.item);
item.setText(dataSource.get(position));
return convertView;
}
}
private class BluetoothServerSocketThread extends Thread {
private BluetoothServerSocket bluetoothServerSocket;
private BluetoothSocket clientSocket;
private InputStream inputStream;
private OutputStream outputStream;
public BluetoothServerSocketThread( ) {
//listenUsingRfcommWithServiceRecord(String name, UUID uuid)
// UUID uuid = UUID.randomUUID();
try {
//建立藍芽伺服器,第一個引數是伺服器的名稱,第二個是一個唯一標識當前伺服器的ID,相當於是一個IP地址
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("1508a_Service", uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
try {
clientSocket = bluetoothServerSocket.accept();//監聽客戶端的連結
inputStream = clientSocket.getInputStream();
outputStream = clientSocket.getOutputStream();
while (true) {
byte[] buffer = new byte[1024];
int count = inputStream.read(buffer);
String message = new String(buffer, 0, count, "utf-8");
Looper.prepare();
Toast.makeText(BluetoothActivity.this,message,Toast.LENGTH_LONG).show();
Looper.loop();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
GPS程式碼
package com.example.mydemo;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
public class GpsActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_gps;
private Button btn_back;
private LocationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
initView();
getIntent();
}
private void initView() {
et_gps = (EditText) findViewById(R.id.et_gps);
btn_back = (Button) findViewById(R.id.btn_back);
btn_back.setOnClickListener(this);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//如果GPS沒有開啟,跳轉到GPS介面手動開啟
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "請先開啟GPS", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener);
}
private void updateData(Location location) {
et_gps.setText("緯度:");
et_gps.append(String.valueOf(location.getLongitude()));
et_gps.append("\n經度:");
et_gps.append(String.valueOf(location.getLatitude()));
et_gps.append("\n海拔:");
et_gps.append(String.valueOf(location.getAltitude()));
}
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateData(location);//更新UI
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
if (ActivityCompat.checkSelfPermission(GpsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GpsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location lastKnownLocation = manager.getLastKnownLocation(provider);
updateData(lastKnownLocation);
}
@Override
public void onProviderDisabled(String provider) {
updateData(null);
}
};
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
finish();
break;
}
}
}
APP程式碼
package com.example.mydemo;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
import android.app.Application;
import org.xutils.x;
/**
* Created by Me on 2017/11/22.
*/
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
x.Ext.init(this);
x.Ext.setDebug(true);
}
}
ContentProvider程式碼
package com.example.mydemo;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
/**
* Created by Me on 2017/11/22.
*/
public class MyContentProvider extends ContentProvider {
String path = "content://alice.bw.com.day04_yuekaodemo/data";
SQLiteDatabase database;
@Override
public boolean onCreate() {
MySQliteOpenHelper helper = new MySQliteOpenHelper(getContext());
database = helper.getWritableDatabase();
return false;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
Cursor cursor = database.query("data", null, null, null, null, null, null);
return cursor;
}
@Nullable
@Override
public String getType(Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
long test = database.insert("data", null, values);
Uri uri1 = ContentUris.withAppendedId(Uri.parse(path), test);
return uri1;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int test = database.delete("data", selection, selectionArgs);
return test;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int test = database.update("data", values, selection, selectionArgs);
return test;
}
}
RecyclerAdapter程式碼
package com.example.mydemo;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.xutils.x;
import java.util.List;
/**
* Created by Me on 2017/11/22.
*/
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
List<Food.DataBean> list;
Context context;
public MyRecyclerAdapter(List<Food.DataBean> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_layout, null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
x.image().bind(holder.iv,list.get(position).getPic());
holder.tv.setText(list.get(position).getTitle());
}
@Override
public int getItemCount() {
if (list != null){
return list.size();
}
return 0;
}
class ViewHolder extends RecyclerView.ViewHolder{
ImageView iv;
TextView tv;
public ViewHolder(View itemView) {
super(itemView);
iv = (ImageView) itemView.findViewById(R.id.iv);
tv = (TextView) itemView.findViewById(R.id.tv);
}
}
}
SQliteOpenHelper
package com.example.mydemo;
/**
* Created by 暖陽學長 on 2017/11/23.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Me on 2017/11/22.
*/
public class MySQliteOpenHelper extends SQLiteOpenHelper {
private static final String dbName="mydb.db";
private static final int version=1;
public MySQliteOpenHelper(Context context) {
super(context, dbName, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table data(_id integer primary key autoincrement,pic text,title text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
最後,別忘了新增依賴
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'org.xutils:xutils:3.5.0'
compile files('libs/gson-2.2.1.jar')
專案中用到了GSON所以要導一個GSON包