You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Firebase的Android应用多用户按钮权限控制实现问询

实现专属按钮权限的完整方案

Hey there! Since you've got a fixed set of 3 registered users and need to restrict each to their own button, let's walk through a straightforward, reliable implementation using Firebase Auth and either hardcoded mappings (perfect for your small user base) or Firebase Firestore/Realtime Database (for future scalability).

1. 第一步:获取当前登录用户的唯一标识

First, you'll need to grab the currently authenticated user's UID (Firebase's permanent unique user ID) — this is the most reliable way to distinguish between your 3 users, since emails/display names can change but UIDs never do.

Add this code to your Activity's onCreate() (or onStart() to handle account switches seamlessly):

// Kotlin example
import com.google.firebase.auth.FirebaseAuth

class ButtonRestrictionActivity : AppCompatActivity() {
    private lateinit var auth: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_button_restriction)
        
        auth = FirebaseAuth.getInstance()
        val currentUser = auth.currentUser
        
        // Handle unauthenticated users
        currentUser ?: run {
            // Disable all buttons or redirect to login screen
            findViewById<Button>(R.id.user1_btn).isEnabled = false
            findViewById<Button>(R.id.user2_btn).isEnabled = false
            findViewById<Button>(R.id.user3_btn).isEnabled = false
            Toast.makeText(this, "Please log in first", Toast.LENGTH_SHORT).show()
            return
        }
        
        // Pass the user's UID to set up button permissions
        setupButtonAccess(currentUser.uid)
    }
}
// Java example
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class ButtonRestrictionActivity extends AppCompatActivity {
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button_restriction);
        
        auth = FirebaseAuth.getInstance();
        FirebaseUser currentUser = auth.getCurrentUser();
        
        if (currentUser == null) {
            Button user1Btn = findViewById(R.id.user1_btn);
            Button user2Btn = findViewById(R.id.user2_btn);
            Button user3Btn = findViewById(R.id.user3_btn);
            
            user1Btn.setEnabled(false);
            user2Btn.setEnabled(false);
            user3Btn.setEnabled(false);
            
            Toast.makeText(this, "Please log in first", Toast.LENGTH_SHORT).show();
            return;
        }
        
        setupButtonAccess(currentUser.getUid());
    }
}

2. 第二步:映射用户与按钮的权限关系

You have two solid options here, depending on whether you plan to expand your user base later:

选项A:硬编码映射(适合固定3个用户)

Since you only have 3 registered users, hardcoding their UIDs to button IDs is fast and avoids extra database calls. Add this helper method to your Activity:

// Kotlin
private fun setupButtonAccess(userUid: String) {
    val user1Btn = findViewById<Button>(R.id.user1_btn)
    val user2Btn = findViewById<Button>(R.id.user2_btn)
    val user3Btn = findViewById<Button>(R.id.user3_btn)
    
    // Replace these UIDs with your actual 3 users' Firebase UIDs
    val userButtonMap = mapOf(
        "user1_firebase_uid" to user1Btn,
        "user2_firebase_uid" to user2Btn,
        "user3_firebase_uid" to user3Btn
    )
    
    // Disable all buttons first to ensure no accidental access
    listOf(user1Btn, user2Btn, user3Btn).forEach { it.isEnabled = false }
    
    // Enable only the user's assigned button
    userButtonMap[userUid]?.isEnabled = true
}
// Java
private void setupButtonAccess(String userUid) {
    Button user1Btn = findViewById(R.id.user1_btn);
    Button user2Btn = findViewById(R.id.user2_btn);
    Button user3Btn = findViewById(R.id.user3_btn);
    
    // Replace with your actual user UIDs from Firebase Auth
    HashMap<String, Button> userButtonMap = new HashMap<>();
    userButtonMap.put("user1_firebase_uid", user1Btn);
    userButtonMap.put("user2_firebase_uid", user2Btn);
    userButtonMap.put("user3_firebase_uid", user3Btn);
    
    // Disable all buttons initially
    user1Btn.setEnabled(false);
    user2Btn.setEnabled(false);
    user3Btn.setEnabled(false);
    
    // Enable the user's designated button
    Button userAssignedBtn = userButtonMap.get(userUid);
    if (userAssignedBtn != null) {
        userAssignedBtn.setEnabled(true);
    }
}

选项B:Firebase数据库映射(可扩展)

If you might add more users down the line, store user-button mappings in Firebase Firestore or Realtime Database. Here's a Firestore example:

  1. Create a Firestore collection called userPermissions with documents structured like this:
    userPermissions/
      user1_firebase_uid: { allowedButtonId: "user1_btn" }
      user2_firebase_uid: { allowedButtonId: "user2_btn" }
      user3_firebase_uid: { allowedButtonId: "user3_btn" }
    
  2. Fetch the mapping in your Activity:
// Kotlin Firestore example
import com.google.firebase.firestore.FirebaseFirestore

private fun setupButtonAccess(userUid: String) {
    val db = FirebaseFirestore.getInstance()
    val user1Btn = findViewById<Button>(R.id.user1_btn)
    val user2Btn = findViewById<Button>(R.id.user2_btn)
    val user3Btn = findViewById<Button>(R.id.user3_btn)
    
    // Disable all buttons first
    listOf(user1Btn, user2Btn, user3Btn).forEach { it.isEnabled = false }
    
    db.collection("userPermissions").document(userUid)
        .get()
        .addOnSuccessListener { document ->
            val allowedButtonId = document.getString("allowedButtonId")
            when (allowedButtonId) {
                "user1_btn" -> user1Btn.isEnabled = true
                "user2_btn" -> user2Btn.isEnabled = true
                "user3_btn" -> user3Btn.isEnabled = true
            }
        }
        .addOnFailureListener {
            Toast.makeText(this, "Failed to load permissions", Toast.LENGTH_SHORT).show()
        }
}

3. 第三步:处理账号切换场景

Make sure button permissions update if the user logs out or switches accounts. Add this to your Activity's onStart() method:

// Kotlin
override fun onStart() {
    super.onStart()
    val currentUser = auth.currentUser
    currentUser?.let { setupButtonAccess(it.uid) } ?: run {
        // Disable all buttons if no user is logged in
        findViewById<Button>(R.id.user1_btn).isEnabled = false
        findViewById<Button>(R.id.user2_btn).isEnabled = false
        findViewById<Button>(R.id.user3_btn).isEnabled = false
    }
}

关键注意事项

  • Never use display names/emails for permission checks: Users can modify these, but Firebase UIDs are permanent and immutable.
  • Lock down database security: If using Firestore/RTDB, set security rules to ensure users can only read their own permission document (e.g., allow read: if request.auth.uid == resource.id;).
  • Test edge cases: Verify buttons stay disabled when users log out, and re-enable correctly when they log back in with their account.

内容的提问来源于stack exchange,提问作者Данил Филиппов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:31:46