Android之Bmob移動后端雲服務器


源碼下載:http://download.csdn.net/download/jjhahage/10034519

PS:一般情況下,我們在寫android程序的時候,想要實現登錄注冊功能,可以選擇自己用servlet作為服務端來實現過濾沒有注冊過的用戶,但是太麻煩,而且不是隨時都可以用的。這里介紹一個移動后端雲服務器平台bmob,這不僅可以實現雲數據庫儲存,還可以獲取手機驗證等,隨時隨地都很輕松,下面寫一個小demo,實現一個登陸注冊功能,認識增刪查改。下面我稍微寫一個例子,簡單實現注冊登錄功能。

1:首先到bmob官網,注冊一個賬號,里面創建一個項目,如圖:

2:創建一個android項目,(AndroidStudio)

(1):添加依賴:在app下的build.gradle中添加

compile 'cn.bmob.android:bmob-sdk:3.4.6'
compile 'com.squareup.okhttp:okhttp:2.4.0'//CDN文件服務使用okhttp相關包進行文件的上傳和下載(必填)
compile 'com.squareup.okio:okio:1.4.0'

 

sourceSets {
main.jniLibs.srcDirs = ['libs']
}

useLibrary 'org.apache.http.legacy'

 

 

位置如圖:


(2)添加權限:

<!--允許聯網-->

 

<uses-permission android:name="android.permission.INTERNET"/>
<!--獲取GSM(2g)、WCDMA(聯通3g)等網絡狀態的信息 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--獲取wifi網絡狀態的信息-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<!--保持CPU運轉,屏幕和鍵盤燈有可能是關閉的,用於文件上傳和下載-->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<!--獲取sd卡寫的權限,用於文件上傳和下載-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--允許讀取手機狀態 用於創建BmobInstallation-->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

 

 

 

(3):添加maven,到指定的雲庫

 

maven { url "https://raw.github.com/bmob/bmob-android-sdk/master"}

 

 

(4:)初始化:

 

Bmob.initialize(this,"你的 應用ID");

3:下面就是代碼了

寫一個實體類person,

 

package cn.day1.model;

import cn.bmob.v3.BmobObject;

/**
 * Created by CMusketeer on 17/10/22.
 */
public class Person extends BmobObject {
    private String name;
    private String password;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

 

寫三個布局,分別是注冊頁面,登錄頁面,登錄成功跳轉的頁面

 

activity_main.xml

 

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
android:orientation="vertical"
    tools:context="cn.day1.bmobtest1.MainActivity">

    <TextView
        android:gravity="center"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:text="登錄" />
    <EditText
        android:id="@+id/id_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="username"/>

    <EditText
        android:id="@+id/id_userpassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/id_ok"
            android:layout_width="0dp"
            android:text="登錄"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

        <Button
            android:id="@+id/id_register"
            android:text="注冊"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

注冊頁面:register_layout.xml,先把各頁面都寫了,后續就好辦了。

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="cn.day1.bmobtest1.MainActivity">

    <TextView
        android:gravity="center"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:text="注冊中心" />
    <EditText
        android:id="@+id/id_register_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="username"/>

    <EditText
        android:id="@+id/id_register_userpassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <Button
            android:id="@+id/id_register_ok"
            android:text="注冊"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>
</LinearLayout>

 

登錄成功頁面:success.xml
<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="成功登錄"
        android:gravity="center"
        android:textSize="50dp"/>

</LinearLayout>

注冊Activity,RegisterActivity.java  功能:增

這里是一個簡單的注冊,里面沒有加判斷,所以,一個號可以重復注冊,但是只有唯一ID。

package cn.day1.bmobtest1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import cn.bmob.v3.listener.SaveListener;
import cn.day1.model.Person;

/**
 * Created by CMusketeer on 17/10/22.
 */
public class RegisterActivity extends Activity {

    private TextView register_user;
    private TextView register_password;
    private Button register_ok;
    private Person p2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);
        addControl();//加載控件

        addRegisterShow();//注冊方法



    }

    private void addRegisterShow() {
        register_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String rUser=register_user.getText().toString().trim();
                String rPassword=register_password.getText().toString().trim();

                //判斷用戶名和密碼是否為空,如果為空則不能進去。
                if(rUser.length()>0&&rPassword.length()>0){
                    p2 = new Person();
                    p2.setName(rUser);
                    p2.setPassword(rPassword);
                    //插入方法
                    p2.save(RegisterActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            // TODO Auto-generated method stub
                            register_password.setText("");
                            register_user.setText("");
                            Toast.makeText(RegisterActivity.this, "添加數據成功,返回objectId為:" + p2.getObjectId(), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            // TODO Auto-generated method stub
                            Toast.makeText(RegisterActivity.this, "創建數據失敗:" + msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    Toast.makeText(RegisterActivity.this, "用戶名或者密碼不能為空", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void addControl() {
        register_user = (TextView) findViewById(R.id.id_register_username);
        register_password = (TextView) findViewById(R.id.id_register_userpassword);
        register_ok = (Button) findViewById(R.id.id_register_ok);


    }
}

 

登錄頁面:MainActivity.java   功能:查

 

 

package cn.day1.bmobtest1;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.day1.model.Person;

public class MainActivity extends AppCompatActivity {

    private Person p2;
    private TextView lgUser;
    private TextView lgPassword;
    private Button btn_ok;
    private Button btn_rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bmob.initialize(this, "你的 應用id");
        setContentView(R.layout.activity_main);

        addControl();
        addLogin();




    }

    private void addLogin() {
        btn_rg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,RegisterActivity.class);
                startActivity(intent);
            }
        });

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobQuery<Person> query=new BmobQuery<Person>();
                query.findObjects(MainActivity.this,new FindListener<Person>(){

                    String lgU=lgUser.getText().toString().trim();
                    String lgp=lgPassword.getText().toString().trim();
                    int panduan=1;

                    @Override
                    public void onSuccess(List<Person> list) {
                        for(int i=0;i<list.size();i++){
                                String name=list.get(i).getName();

                                String password=list.get(i).getPassword();
                            Log.e("user","唯一 id:"+list.get(i).getObjectId()+"----"+name+"---"+password);
                                if(name.equals(lgU) && password.equals(lgp)){
                                    Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_SHORT).show();
                                    panduan=2;
                                    //成功后panduan等於2,則跳出該循環,並且把輸入快都清空,跳轉到指定頁面
                                    lgUser.setText("");
                                    lgPassword.setText("");
                                    Intent intent=new Intent(MainActivity.this,Success.class);
                                    startActivity(intent);

                                    break;
                                }

                        }
                        if(panduan==1){
                            Toast.makeText(MainActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show();
                        }
                    }

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

                    }
                });
            }
        });


    }

    private void addControl() {

        lgUser = (TextView) findViewById(R.id.id_username);
        lgPassword = (TextView) findViewById(R.id.id_userpassword);
        btn_ok = (Button) findViewById(R.id.id_ok);
        btn_rg = (Button) findViewById(R.id.id_register);
    }
}

 


登錄成功頁面 Success.java

 

 

package cn.day1.bmobtest1;

import android.app.Activity;
import android.os.Bundle;

/**
 * Created by CMusketeer on 17/10/22.
 */
public class Success extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.success);
    }
}

 

總結:

 

唯一id的獲取可以通過用戶名來獲取,當用戶輸入用戶名時,只要數據庫中用戶名和輸入的一致,則就可以list.get(i).getObjectId()

 

處理增刪查改
增:
person = new Person();
person.setName(user);
person.setAddress(password);
person.save(new SaveListener<String>() {
    @Override
    public void done(String s, BmobException e) {
        if(e == null){
            Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();

           
        }
        else{

        }
    }
});
刪
Id可以通過查處所有的,從而得到id
id=list.get(i).getObjectId();
 person = new Person();
person.delete(id, new UpdateListener() {
 @Override
 public void done(BmobException e) {
      if(e==null){
 Log.e("sss","刪除成功"); }
  }
  });


查 :和上面的查不大一樣,這也是一種方法
//查詢所有,
query.findObjects(new FindListener<Person>() {
    @Override
    public void done(List<Person> list, BmobException e) {
}}
//查詢單個
query.getObject(id,new listener)
改
person.setName(“111”);
person.update(id,new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if(e==null){
//                                        Toast.makeText(MainActivity.this, "更改成功", Toast.LENGTH_SHORT).show();
                                        Log.e("sss","更改成功");
                                    }
                                }

 

效果圖:

 




 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM