android打開數據連接
Ⅰ Android5.1怎麼用代碼實現打開數據連接。。。在線急等
java"> publicvoidsetMobileDataState(Contextcontext,booleanenabled){
=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
try{
MethodsetDataEnabled=telephonyService.getClass().getDeclaredMethod("setDataEnabled",boolean.class);
if(null!=setDataEnabled){
setDataEnabled.invoke(telephonyService,enabled);
}
}catch(Exceptione){
e.printStackTrace();
}
}
(Contextcontext){
=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
try{
MethodgetDataEnabled=telephonyService.getClass().getDeclaredMethod("getDataEnabled");
if(null!=getDataEnabled){
return(Boolean)getDataEnabled.invoke(telephonyService);
}
}catch(Exceptione){
e.printStackTrace();
}
returnfalse;
}
<uses-permissionandroid:name="android.permission.MODIFY_PHONE_STATE"/>
注意: 要使用系統簽名, 否則許可權不夠
另特別注意, 有些支持雙卡的手機, 在用此代碼前要開過數據連接, 不然不知道是開哪張卡
Ⅱ 如何在Android開發中用HttpClient連接網路數據
HttpClient網路訪問
一、HttpClient網路訪問:
(一)、簡介:
1、Apache組織提供了HttpClient項目,可以實現網路訪問。在Android中,成功集成了HttpClient,所以在Android中可以直接使用HttpClient訪問網路。
2、與HttpURLConnection相比,HttpClient將前者中的輸入、輸出流操作,統一封裝成HttpGet、HttpPost、HttpRequest類。
HttpClient:網路連接對象;
HttpGet:代表發送GET請求;
HttpPost:代表發送POST請求;
HttpResponse:代表處理伺服器響應的對象。
HttpEntity對象:該對象中包含了伺服器所有的返回內容。
3、使用步驟:(六部曲)【重點】
創建HttpClient對象:通過實例化DefaultHttpClient獲得;
創建HttpGet或HttpPost對象:通過實例化 HttpGet或HttpPost 獲得,而構造方法的參數是urlstring(即需要訪問的網路url地址)。也可以通過調用setParams()方法來添加請求參數;
調用HttpClient對象的execute()方法,參數是剛才創建的 HttpGet或HttpPost對象 ,返回值是HttpResponse對象;
通過response對象中的getStatusLine()方法和getStatusCode()方法獲取伺服器響應狀態是否是200。
調用 HttpResponse對象的getEntity()方法,返回HttpEntity對象。而該對象中包含了伺服器所有的返回內容。
藉助EntityUtils的toString()方法或toByteArray()對 HttpEntity對象進行處理,也可以通過IO流對 HttpEntity對象進行操作。
(二)、封裝HttpClientHelper工具類:
public class HttpClientHelper {
public static HttpClient checkNetwork(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return httpClient;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:實現網路訪問文件,將獲取到數據儲存在文件流中
*
* @param url
* :訪問網路的url地址
* @return inputstream
*/
public static InputStream loadFileFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
return entity.getContent();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:實現網路訪問文件,將獲取到的數據存在位元組數組中
*
* @param url
* :訪問網路的url地址
* @return byte[]
*/
public static byte[] loadByteFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("====>" + e.toString());
}
return null;
}
/**
* 作用:實現網路訪問文件,返回字元串
*
* @param url
* :訪問網路的url地址
* @return String
*/
public static String loadTextFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:實現網路訪問文件,先給伺服器通過「GET」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。
* 第二個參數格式為:username=wangxiangjun&password=123456
* @return byte[]
*/
public static byte[] doGetSubmit(String url, String params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url + "?" + params);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:實現網路訪問文件,先給伺服器通過「POST」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。 第二個參數為:List<NameValuePair>
* @return byte[]
*/
public static byte[] doPostSubmit(String url, List<NameValuePair> params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost requestPost = new HttpPost(url);
try {
requestPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(requestPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 作用:實現網路訪問文件,先給伺服器通過「POST」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。 Map<String , Object>
* @return byte[]
*/
public static byte[] doPostSubmit(String url, Map<String, Object> params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost requestPost = new HttpPost(url);
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
try {
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
BasicNameValuePair nameValuePair = new BasicNameValuePair(
key, value);
parameters.add(nameValuePair);
}
}
requestPost
.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
HttpResponse httpResponse = httpClient.execute(requestPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Ⅲ 如何連接android資料庫
關系型資料庫sqlite3,它是一個支持SQL輕量級的嵌入式資料庫,在嵌入式操作上有很廣泛的,WM採用的也是SQLite3
關於過於、原理方面的東西在這篇文章里不會提到,但是如果你想能夠快速的學會操作SQLite3,那這就是你要找的文章!
首先,我們看一下api,所有資料庫相關的介面、類都在.database和android.database.sqlite兩個包下,雖然只有兩個包,但是如果你英文不好或是太懶的話也要迷茫一段時間,其實,我們真正用的到的沒有幾個!
1、SQLiteOpenHelper (android.database.sqlite.SQLiteOpenHelper)
這是一個抽象類,關於抽象類我們都知道,如果要使用它,一定是繼承它!
這個類的方法很少,有一個構造方法
SQLiteOpenHelper(android.content.Context context, java.lang.String name,android.database.sqlite.SQLiteDatabase.CursorFactory factory, int version);
參數不做過多的解釋,CursorFactory一般直接傳null就可以
public void onCreate(SQLiteDatabase db)
此方法在創建資料庫是被調用,所以,應該把創建表的操作放到這個方法裡面,一會兒在後面我們會再詳細的說如何創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
從方法名上我們就能知道這個方法是執行更新的,沒錯,當version改變是系統會調用這個方法,所以在這個方法里應該執行刪除現有表,然後手動調用onCreate的操作
SQLiteDatabase getReadableDatabase()
可讀的SQLiteDatabase對象
SQLiteDatabase getWritableDatabase()
獲取可寫的SQLiteDatabase對象
2、SQLiteDatabase(android.database.sqlite.SQLiteDatabase)
關於操作資料庫的工作(增、刪、查、改)都在這個類里
execSQL(sql)
執行SQL語句,用這個方法+SQL語句可以非常方便的執行增、刪、查、改
除此之外,Android還提供了功過方法實現增、刪、查、改
long insert(TABLE_NAME, null, contentValues)添加記錄
int delete(TABLE_NAME, where, whereValue)刪除記錄
int update(TABLE_NAME, contentValues, where, whereValue) 更新記錄
Cursor query(TABLE_NAME, null, null, null, null, null, null) 查詢記錄
除此之外,還有很多方法,如:beginTransaction()開始事務、endTransaction()結束事務...有興趣的可以自己看api,這里就不多贅述了
3、Cursor(android.database.Cursor)
游標(介面),這個很熟悉了吧,Cursor里的方法非常多,常用的有:
boolean moveToPosition(position)將指針移動到某記錄
getColumnIndex(Contacts.People.NAME)按列名獲取id
int getCount()獲取記錄總數
boolean requery()重新查詢
boolean isAfterLast()指針是否在末尾
boolean isBeforeFirst()時候是開始位置
boolean isFirst()是否是第一條記錄
boolean isLast()是否是最後一條記錄
boolean moveToFirst()、 boolean moveToLast()、 boolean moveToNext()同moveToPosition(position)
4、SimpleCursorAdapter(android.widget.SimpleCursorAdapter)
也許你會奇怪了,之前我還說過關於資料庫的操作都在database和database.sqlite包下,為什麼把一個Adapter放到這里,如果你用過Android的SQLite3,你一定會知道
,這是因為我們對資料庫的操作會經常跟列表聯系起來
經常有朋友會在這出錯,但其實也很簡單
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list,
myCursor,
new String[] ,
new int[]);
my.setAdapter(adapter);
一共5個參數,具體如下:
參數1:Content
參數2:布局
參數3:Cursor游標對象
參數4:顯示的欄位,傳入String[]
參數5:顯示欄位使用的組件,傳入int[],該數組中是TextView組件的id
到這里,關於資料庫的操作就結束了,但是到目前為止我只做了翻譯的工作,有些同學可能還是沒有掌握,放心,下面我們一起順著正常開發的思路理清一下頭緒!
前面的只是幫沒做過的朋友做下普及,下面才是你真正需要的!
一、寫一個類繼承SQLiteOpenHelpe
public class DatabaseHelper extends SQLiteOpenHelper
構造方法:
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
在onCreate方法里寫建表的操作
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE tb_test (_id INTEGER DEFAULT '1' NOT NULL PRIMARY KEY AUTOINCREMENT,class_jb TEXT NOT NULL,class_ysbj TEXT NOT NULL,title TEXT NOT NULL,content_ysbj TEXT NOT NULL)";
db.execSQL(sql);//需要異常捕獲
}
在onUpgrade方法里刪除現有表,然後手動調用onCtreate創建表
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "drop table "+tbname;
db.execSQL(sql);
onCreate(db);
}
對表增、刪、查、改的方法,這里用的是SQLiteOpenHelper提供的方法,也可以用sql語句實現,都是一樣的
關於獲取可讀/可寫SQLiteDatabase,我不說大家也應該會想到,只有查找才會用到可讀的SQLiteDatabase
/**
* 添加數據
*/
public long insert(String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();//獲取可寫SQLiteDatabase對象
//ContentValues類似map,存入的是鍵值對
ContentValues contentValues = new ContentValues();
contentValues.put("tname", tname);
contentValues.put("tage", tage);
contentValues.put("ttel", ttel);
return db.insert(tbname, null, contentValues);
}
/**
* 刪除記錄
* @param _id
*/
public void delete(String _id){
SQLiteDatabase db= getWritableDatabase();
db.delete(tbname,
"_id=?",
new String[]);
}
/**
* 更新記錄的,跟插入的很像
*/
public void update(String _id,String tname, int tage, String ttel){
SQLiteDatabase db= getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("tname", tname);
contentValues.put("tage", tage);
contentValues.put("ttel", ttel);
db.update(tbname, contentValues,
"_id=?",
new String[]);
}
/**
* 查詢所有數據
* @return Cursor
*/
public Cursor select(){
SQLiteDatabase db = getReadableDatabase();
return db.query(
tbname,
new String[],
null,
null, null, null, "_id desc");
}
關於db.query方法的參數,有很多,為了防止大家弄亂,我簡單說一下
參數1:表名
參數2:返回數據包含的列信息,String數組里放的都是列名
參數3:相當於sql里的where,sql里where後寫的內容放到這就行了,例如:tage>?
參數4:如果你在參數3里寫了?(知道我為什麼寫tage>?了吧),那個這里就是代替?的值 接上例:new String[]
參數5:分組,不解釋了,不想分組就傳null
參數6:having,想不起來的看看SQL
參數7:orderBy排序
到這里,你已經完成了最多的第一步!我們來看看都用到了那些類:
SQLiteOpenHelper我們繼承使用的
SQLiteDatabase增刪查改都離不開它,即使你直接用sql語句,也要用到execSQL(sql)
二、這里無非是對DatabaseHelper類定義方法的調用,沒什麼可說的,不過我還是對查詢再嘮叨幾句吧
Android查詢出來的結果一Cursor形式返回
cursor = sqLiteHelper.select();//是不是很簡單?
查詢出來的cursor一般會顯示在listView中,這就要用到剛才提到的SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_row,
cursor,
new String[],
new int[]
);
裡面帶有實例。自己好好學習吧!
Ⅳ android開發資料庫怎麼連接
這種方式通常連接一個外部的資料庫,第一個參數就是資料庫文件,這個資料庫不是當前項目中生成的,通常放在項目的Assets目錄下,當然也可以在手機內,如上面參數那個目錄,前提是那個文件存在且你的程序有訪問許可權。
另一種使用資料庫的方式是,自己創建資料庫並創建相應的資料庫表,參考下面的代碼:
{
//構造,調用父類構造,資料庫名字,版本號(傳入更大的版本號可以讓資料庫升級,onUpgrade被調用)
publicDatabaseHelper(Contextcontext){
super(context,DatabaseConstant.DATABASE_NAME,null,DatabaseConstant.DATABASE_VERSION);
}
//資料庫創建時調用,裡面執行表創建語句.
@Override
publicvoidonCreate(SQLiteDatabasedb){
db.execSQL(createVoucherTable());
}
//資料庫升級時調用,先刪除舊表,在調用onCreate創建表.
@Override
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
db.execSQL("DROPTABLEIFEXISTS"+DatabaseConstant.TABLE_NAME);
onCreate(db);
}
//生成創建表的SQL語句
(){
StringBuffersb=newStringBuffer();
sb.append("CREATETABLE").append(DatabaseConstant.TABLE_NAME).append("(").append(「ID」)
.append("TEXTPRIMARYKEY,")
.append(「USER_ID」).append("INTEGER,").append(「SMS_CONTENT」).append("TEXT)");
returnsb.toString();
}
}
繼承SQLiteOpenHelper並實現裡面的方法.
之後:
//得到資料庫助手類
helper = new DatabaseHelper(context);
//通過助手類,打開一個可讀寫的資料庫連接
SQLiteDatabase database = helper.getReadableDatabase();
//查詢表中所有記錄
database.query(DatabaseConstant.TABLE_NAME, null, null, null, null, null, null);
Ⅳ Android客戶端怎麼與伺服器資料庫連接
不能與資料庫連接的
Android客戶端不能直接與伺服器資料庫連接。資料庫是需要非常大的內存,安裝之後有好幾G,連接資料庫要有一個像SQLServer里的webservice,這樣的一個橋梁來間接訪問。就是在伺服器運行一個服務端程序,該服務端程序通過接收來自android客戶端的指令,對資料庫進行操作。
客戶端的http請求可以通過 HttpClient類實現,在anddroid 4.0之後,客戶端的網路請求已經不被允許在主線程中運行,所以還需注意另開啟一個子線程進行網路請求。
(5)android打開數據連接擴展閱讀:
Android安全許可權機制:
Android默認設置下,所有應用都沒有許可權對其他應用、系統或用戶進行較大影響的操作。這其中包括讀寫用戶隱私數據(聯系人或電子郵件),讀寫其他應用文件,訪問網路或阻止設備待機等。安裝應用時,在檢查程序簽名提及的許可權,且經過用戶確認後,軟體包安裝器會給予應用許可權。
下載一款Android應用通常會要求如下的許可權:撥打電話、發送簡訊或彩信、修改/刪除SD卡上的內容、讀取聯系人的信息、讀取日程信的息,寫入日程數據、讀取電話狀態或識別碼、精確的(基於GPS)地理位置、模糊的(基於網路獲取)地理位置、創建藍牙連接、
還有對互聯網的完全訪問、查看網路狀態,查看WiFi狀態、避免手機待機、修改系統全局設置、讀取同步設定、開機自啟動、重啟其他應用、終止運行中的應用、設定偏好應用、震動控制、拍攝圖片等。
Ⅵ Android 開發。。。如何連接到伺服器上的mysql資料庫
1、打開Tableau軟體。
Ⅶ 為何Android手機在打開數據連接時會有數據流量產生
打開數據連接確實會有流量產生,因為打開數據連接時跟
網路伺服器
是有交互的。
另外手機中的
天氣插件
、新聞插件及
應用商店
等軟體的升級檢測,都會產生一定的數據流量,所以要建議用戶訂制套餐包。
Ⅷ android怎麼鏈接資料庫mysql
有點多請耐心看完。
希望能幫助你,還請及時採納謝謝。
一.前言
android連接資料庫的方式有兩種,第一種是通過連接伺服器,再由伺服器讀取資料庫來實現數據的增刪改查,這也是我們常用的方式。第二種方式是android直接連接資料庫,這種方式非常耗手機內存,而且容易被反編譯造成安全隱患,所以在實際項目中不推薦使用。
二.准備工作
1.載入外部jar包
在Android工程中要使用jdbc的話,要導入jdbc的外部jar包,因為在Java的jdk中並沒有jdbc的api,我使用的jar包是mysql-connector-java-5.1.18-bin.jar包,網路上有使用mysql-connector-java-5.1.18-bin.jar包的,自己去用的時候發現不兼容,所以下載了比較新版本的,jar包可以去官網下載,也可以去網路,有很多前人們上傳的。
2.導入jar包的方式
方式一:
可以在項目的build.gradle文件中直接添加如下語句導入
compile files('libs/mysql-connector-java-5.1.18-bin.jar')
方式二:下載jar包復制到項目的libs目錄下,然後右鍵復制過來的jar包Add as libs
三.建立資料庫連接
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jdbc);
new Thread(runnable).start();
}
Handler myHandler=new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bundle data=new Bundle();
data=msg.getData();
//System.out.println("id:"+data.get("id").toString()); //輸出第n行,列名為「id」的值
Log.e("TAG","id:"+data.get("id").toString());
TextView tv= (TextView) findViewById(R.id.jdbc);
//System.out.println("content:"+data.get("content").toString());
}
};
Runnable runnable=new Runnable() {
private Connection con = null;
@Override
public void run() {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
//引用代碼此處需要修改,address為數據IP,Port為埠號,DBName為數據名稱,UserName為資料庫登錄賬戶,Password為資料庫登錄密碼
con =
//DriverManager.getConnection("jdbc:mysql://192.168.1.202:3306/b2b", "root", "");
DriverManager.getConnection("jdbc:mysql://http://192.168.1.100/phpmyadmin/index.php:8086/b2b",
UserName,Password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
testConnection(con); //測試資料庫連接
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testConnection(Connection con1) throws java.sql.SQLException {
try {
String sql = "select * from ecs_users"; //查詢表名為「oner_alarm」的所有內容
Statement stmt = con1.createStatement(); //創建Statement
ResultSet rs = stmt.executeQuery(sql); //ResultSet類似Cursor
//<code>ResultSet</code>最初指向第一行
Bundle bundle=new Bundle();
while (rs.next()) {
bundle.clear();
bundle.putString("id",rs.getString("userid"));
//bundle.putString("content",rs.getString("content"));
Message msg=new Message();
msg.setData(bundle);
myHandler.sendMessage(msg);
}
rs.close();
stmt.close();
} catch (SQLException e) {
} finally {
if (con1 != null)
try {
con1.close();
} catch (SQLException e) {}
}
}
};
注意:
在Android4.0之後,不允許在主線程中進行比較耗時的操作(連接資料庫就屬於比較耗時的操作),需要開一個新的線程來處理這種耗時的操作,沒新線程時,一直就是程序直接退出,開了一個新線程處理直接,就沒問題了。
當然,連接資料庫是需要網路的,千萬別忘了添加訪問網路許可權:
<uses-permission android:name=」android.permission.INTERNET」/>
四.bug點
1.導入的jar包一定要正確
2.連接資料庫一定要開啟新線程
3.資料庫的IP一定要是可以ping通的,區域網地址手機是訪問不了的
4.資料庫所在的伺服器是否開了防火牆,阻止了訪問
————————————————
版權聲明:本文為CSDN博主「shuaiyou_comon」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/shuaiyou_comon/article/details/75647355