AI Hunter
Member
Mục tiêu hôm nay:
Mở Terminal tại thư mục chứa dự án Jarvis, chạy lệnh sau để tạo folder mới cho App:
Sau đó cài thêm thư viện để gọi API và làm đẹp:
React Native khác React Web một chút:
Mở file
Bước 1: Chạy Server phát triển
Tại Terminal trên máy tính:
Một mã QR Code khổng lồ sẽ hiện ra trên màn hình Terminal.
Bước 2: Quét mã
Bước 3: Trải nghiệm
Điện thoại của bạn sẽ load ứng dụng (lần đầu mất khoảng 1-2 phút để tải bundle).
Sau khi load xong, bạn sẽ thấy giao diện Jarvis màu đen-xanh cực ngầu ngay trên tay mình.
*Lưu ý nếu lỗi kết nối:* Đảm bảo điện thoại và máy tính đang bắt chung một Wifi. Kiểm tra lại địa chỉ IP trong phần code
Vậy là bạn đã mang Jarvis từ "đám mây" xuống "túi quần".
Bây giờ dù bạn đang nằm trên giường, đi vệ sinh hay ngồi phòng khách, chỉ cần rút điện thoại ra là có thể chat với Jarvis.
Tuy nhiên, gõ phím trên điện thoại khá là mỏi tay.
Một trợ lý ảo xịn là phải nói chuyện được bằng miệng.
- Tạo một App Mobile giao diện Dark Mode "ngầu lòi".
- Chạy được trên cả Android và iOS.
- Kết nối với "Bộ não" Jarvis (FastAPI) đang chạy trên VPS (hoặc máy tính).
1. Chuẩn bị công cụ
- Trên điện thoại: Vào App Store (iOS) hoặc CH Play (Android), tải ứng dụng tên là Expo Go.
- Trên máy tính: Cần có Node.js (đã cài ở Season 2).
2. Khởi tạo dự án Mobile
Mở Terminal tại thư mục chứa dự án Jarvis, chạy lệnh sau để tạo folder mới cho App:
Mã:
npx create-expo-app jarvis-mobile
cd jarvis-mobile
Sau đó cài thêm thư viện để gọi API và làm đẹp:
Mã:
npm install axios lucide-react-native
3. Viết Code giao diện (The Mobile Suit)
React Native khác React Web một chút:
- Thay vì
<div>, ta dùng<View>. - Thay vì
<p>, ta dùng<Text>. - Thay vì
onClick, ta dùngonPress.
Mở file
App.js (hoặc app/(tabs)/index.tsx tùy phiên bản Expo, thường là App.js ở bản cơ bản), xóa hết và dán code sau:
JavaScript:
import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity, FlatList, SafeAreaView, ActivityIndicator, KeyboardAvoidingView, Platform, StatusBar } from 'react-native';
import axios from 'axios';
// --- CẤU HÌNH ---
// Nếu chạy Localhost: Hãy dùng IP LAN của máy tính (VD: 192.168.1.5).
// KHÔNG DÙNG 'localhost' hay '127.0.0.1' vì điện thoại sẽ hiểu là chính nó.
// Nếu đã có VPS: Điền IP VPS vào đây (VD: http://123.45.67.89:8000/chat).
const API_URL = "http://192.168.1.X:8000/chat";
const API_TOKEN = "sieumatkhau123456";
export default function App() {
const [messages, setMessages] = useState([
{ id: '1', role: 'bot', text: 'Jarvis Mobile sẵn sàng. Chào sếp!' }
]);
const [input, setInput] = useState('');
const [loading, setLoading] = useState(false);
const sendMessage = async () => {
if (!input.trim()) return;
const userMsg = { id: Date.now().toString(), role: 'user', text: input };
setMessages(prev => [...prev, userMsg]);
setInput('');
setLoading(true);
try {
const res = await axios.post(API_URL,
{ message: userMsg.text },
{ headers: { Authorization: `Bearer ${API_TOKEN}` } }
);
const botMsg = { id: (Date.now() + 1).toString(), role: 'bot', text: res.data.answer };
setMessages(prev => [...prev, botMsg]);
} catch (error) {
const errorMsg = { id: (Date.now() + 1).toString(), role: 'bot', text: '❌ Lỗi kết nối: ' + error.message };
setMessages(prev => [...prev, errorMsg]);
} finally {
setLoading(false);
}
};
const renderItem = ({ item }) => (
<View style={[
styles.msgBubble,
item.role === 'user' ? styles.userBubble : styles.botBubble
]}>
<Text style={styles.msgText}>{item.text}</Text>
</View>
);
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" />
{/* HEADER */}
<View style={styles.header}>
<Text style={styles.headerTitle}>J.A.R.V.I.S</Text>
<Text style={styles.status}>● ONLINE</Text>
</View>
{/* CHAT LIST */}
<FlatList
data={messages}
renderItem={renderItem}
keyExtractor={item => item.id}
contentContainerStyle={styles.chatList}
/>
{/* LOADING */}
{loading && <ActivityIndicator size="small" color="#00f0ff" style={{marginBottom: 10}}/>}
{/* INPUT AREA */}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.inputContainer}
>
<TextInput
style={styles.input}
placeholder="Nhập lệnh..."
placeholderTextColor="#555"
value={input}
onChangeText={setInput}
/>
<TouchableOpacity style={styles.sendBtn} onPress={sendMessage}>
<Text style={styles.sendBtnText}>GỬI</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#050505', // Màu đen thẫm
},
header: {
padding: 20,
borderBottomWidth: 1,
borderBottomColor: '#00f0ff33',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 30,
},
headerTitle: {
color: '#00f0ff', // Màu Cyan Jarvis
fontSize: 24,
fontWeight: 'bold',
letterSpacing: 2,
fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace',
},
status: {
color: '#00ff00',
fontSize: 12,
},
chatList: {
padding: 15,
},
msgBubble: {
maxWidth: '80%',
padding: 12,
borderRadius: 10,
marginBottom: 10,
},
userBubble: {
alignSelf: 'flex-end',
backgroundColor: '#00f0ff22', // Cyan nhạt
borderColor: '#00f0ff',
borderWidth: 1,
},
botBubble: {
alignSelf: 'flex-start',
backgroundColor: '#333',
borderWidth: 1,
borderColor: '#555',
},
msgText: {
color: '#fff',
fontSize: 16,
},
inputContainer: {
flexDirection: 'row',
padding: 15,
borderTopWidth: 1,
borderTopColor: '#333',
backgroundColor: '#050505',
},
input: {
flex: 1,
backgroundColor: '#111',
color: '#00f0ff',
borderWidth: 1,
borderColor: '#00f0ff55',
borderRadius: 20,
paddingHorizontal: 15,
paddingVertical: 10,
marginRight: 10,
},
sendBtn: {
backgroundColor: '#00f0ff',
justifyContent: 'center',
paddingHorizontal: 20,
borderRadius: 20,
},
sendBtnText: {
color: '#000',
fontWeight: 'bold',
},
});
4. Chạy ứng dụng (Magic Time)
Bước 1: Chạy Server phát triển
Tại Terminal trên máy tính:
Mã:
npx expo start
Bước 2: Quét mã
- Android: Mở app Expo Go, chọn "Scan QR Code" và quét mã trên màn hình máy tính.
- iPhone: Mở Camera mặc định, quét mã QR -> Nó sẽ tự hỏi mở bằng Expo Go không.
Bước 3: Trải nghiệm
Điện thoại của bạn sẽ load ứng dụng (lần đầu mất khoảng 1-2 phút để tải bundle).
Sau khi load xong, bạn sẽ thấy giao diện Jarvis màu đen-xanh cực ngầu ngay trên tay mình.
*Lưu ý nếu lỗi kết nối:* Đảm bảo điện thoại và máy tính đang bắt chung một Wifi. Kiểm tra lại địa chỉ IP trong phần code
API_URL.Tổng kết Tập 1
Vậy là bạn đã mang Jarvis từ "đám mây" xuống "túi quần".
Bây giờ dù bạn đang nằm trên giường, đi vệ sinh hay ngồi phòng khách, chỉ cần rút điện thoại ra là có thể chat với Jarvis.
Tuy nhiên, gõ phím trên điện thoại khá là mỏi tay.
Một trợ lý ảo xịn là phải nói chuyện được bằng miệng.
Bài viết liên quan