Chào mừng đến với Diễn đàn lập trình - Cộng đồng lập trình.
Kết quả 1 đến 6 của 6
  1. #1
    Ngày tham gia
    Sep 2015
    Bài viết
    0

    Cách chuyển activity sau khi đăng nhập app bằng acc Facebook

    Em đang làm làm 1 app có chức năng đăng nhập bằng acc facebook, em sử dụng sẵn một cái hàm API của gói Facebook SDK.
    Em có 2 cái layout
    - cái layout 1 có button Login, khi bấm vào sẽ chuyển mở hộp thoại đăng nhập vào app
    Mã:
      btnLogin.setOnClickListener(new OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			login();
    		}
    	});
    login() là hàm API dùng để đăng nhập = acc facebook
    - layout 2 chứa nội dung app
    khổ cái là khi đăng nhập xong thì nó vẫn hiện ra cái layout 1, bây giờ em muốn sau khi đăng nhập xong nó chuyển sang activity 2 chứa layout 2 thì phải làm thế nào hả các bác. (em nghe nói là có thể dùng hàm callback)
    Hy vọng sớm có câu trả lời,Thanks!

  2. #2
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    em đã bắt được sự kiện login thành công chưa ?
    nếu bắt được rồi thì startActivity thứ 2 lên thôi !
    có thể để bắt sự kiện này Activity1 của em sẽ phải implement 1 interface do FB cung cấp

  3. #3
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Login thường là một task tốn thời gian, vì vậy bạn chỉ nên chạy nó trên background task thôi. Chuyển qua Activity khác thì dùng Intent là xong.
    Cách mà mình xử lý (không chắc tối ưu):
    1) Tạo một AsyncTask để log in với tham số là username/password
    2) Trong hàm onPostExecute(), start một Intent chuyển qua activity khác.
    3) Trong lúc login, tạo một hiệu ứng chờ (ví dụ spinning chẳng hạn) và lưu ý chỉ có những task nào chạy dưới 5 sec thì mới được dùng ở Main Thread (tương đuơng với Event Thread bên Java Swing). Ví dụ
    trong hàm onProgressUpdate() chẳng hạn.
    4) Dùng phần FB logIn thì cứ để vào doInBackground rồi chờ kết quả trả về từ onPostExecute.

    Ví dụ:
    MainActivity.java

    Mã:
    package com.cviet.demo; import java.lang.ref.WeakReference;import java.util.ArrayList;import java.util.List; import org.apache.http.NameValuePair;import org.apache.http.message.BasicNameValuePair; import android.opengl.Visibility;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar; public class MainActivity extends Activity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        final Button b = (Button) findViewById(R.id.activity_main_xml_button_login);        final ProgressBar pb = (ProgressBar) findViewById(R.id.activity_main_xml_progressbar);        b.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                pb.setVisibility(0);                new LoginTask(MainActivity.this, "username", "password").execute();            }        });    }     private static class LoginTask extends AsyncTask<Void, Integer, Integer> {        private String username;        private String password;        private WeakReference<MainActivity> ref;         public LoginTask(MainActivity a, String username, String password) {            attach(a);            this.username = username;            this.password = password;        }         @Override        protected void onPreExecute() {        }                @Override        protected void onProgressUpdate(Integer... values) {                    }         @Override        protected Integer doInBackground(Void... voids) {            // dummy data            List<NameValuePair> datas = new ArrayList<NameValuePair>();            datas.add(new BasicNameValuePair("username", username));            datas.add(new BasicNameValuePair("password", password));            // dummy user id            int fakeUserId = 7;            // pretend some work load            sleepFor(10);            return fakeUserId;        }         @Override        protected void onPostExecute(Integer userId) {            ref.get().logIn(userId);            detach();        }         public void attach(MainActivity a) {            ref = new WeakReference<MainActivity>(a);        }         public void detach() {            ref.clear();        }         private void sleepFor(int secs) {            try {                Thread.sleep(secs * 1000);            } catch (InterruptedException e) {                // ignore            }        }     }     public void logIn(Integer id) {        startActivity(new Intent(getApplicationContext(), OtherActivity.class));        finish();    }}
    OtherActivity.java

    Mã:
    package com.cviet.demo; import android.app.Activity;import android.os.Bundle; public class OtherActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.other_activity);    }}
    activity_main.xml

    Mã:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">     <EditText        android:id="@+id/activity_main_xml_edittext_username"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="username"        android:inputType="textPersonName" />     <EditText        android:id="@+id/activity_main_xml_edittext_password"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="password"        android:inputType="textPassword" >    </EditText>     <Button        android:id="@+id/activity_main_xml_button_login"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Log In" />     <ProgressBar        android:id="@+id/activity_main_xml_progressbar"        style="?android:attr/progressBarStyleSmall"        android:visibility="invisible"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /> </LinearLayout>
    other_activity.xml

    Mã:
    <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">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Other Activity">    </TextView></LinearLayout>
    AndroidManifest.xml

    Mã:
    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.cviet.demo"    android:versionCode="1"    android:versionName="1.0" >     <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="10" />     <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >                <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <activity             android:name=".OtherActivity" >           <intent-filter>                <action android:name="com.cviet.demo.OtherActivity" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>    </application> </manifest>

  4. #4
    Ngày tham gia
    Sep 2015
    Đang ở
    Hà Nội
    Bài viết
    0
    cám ơn mọi người nhiều
    em cũng mới newbie thôi, cũng chỉ biết bấm button để chuyển activity thôi chứ chưa biết làm sao để chuyển activity sau khi đăng nhập
    hàm login() của em đây
    Mã:
    public login() {
        // start Facebook Login
        Session.openActiveSession(this, true, new Session.StatusCallback() {
    
          // callback when session changes state
          @Override
          public void call(Session session, SessionState state, Exception exception) {
            if (session.isOpened()) {
    
              // make request to the /me API
              Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
    
                // callback after Graph API response with user object
                @Override
                public void onCompleted(GraphUser user, Response response) {
                  if (user != null) {
                    TextView welcome = (TextView) findViewById(R.id.welcome);
                    welcome.setText("Hello " + user.getName() + "!");
                  }
                }
              });
            }
          }
        });
    }

  5. #5
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    Trích dẫn Gửi bởi LLawliet
    cám ơn mọi người nhiều
    em cũng mới newbie thôi, cũng chỉ biết bấm button để chuyển activity thôi chứ chưa biết làm sao để chuyển activity sau khi đăng nhập
    hàm login() của em đây
    Mã:
    public login() {    // start Facebook Login    Session.openActiveSession(this, true, new Session.StatusCallback() {       // callback when session changes state      @Override      public void call(Session session, SessionState state, Exception exception) {        if (session.isOpened()) {           // make request to the /me API          Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {             // callback after Graph API response with user object            @Override            public void onCompleted(GraphUser user, Response response) {              if (user != null) {                //TextView welcome = (TextView) findViewById(R.id.welcome);                //welcome.setText("Hello " + user.getName() + "!");               startActivity(new Intent(getApplicationContext(), OtherActivity.class));              }            }          });        }      }    });}
    em thử xem , OtherActivity là cái activity thứ 2 của em nhé

  6. #6
    Ngày tham gia
    Sep 2015
    Bài viết
    0
    cảm ơn mọi người, đặc biệt là anh zstar nhé!
    em đã làm theo cách của anh zstar và đã thành công

 

 

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •