Android作为一种开放源代码的操作系统,因其高度可定制性和强大的功能而受到广大开发者的喜爱。本文将为你提供50个实用案例,帮助你轻松上手Android编程。
1. 创建简单的Android应用
1.1 创建项目
在Android Studio中,创建一个新的项目,选择“Empty Activity”作为模板。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
1.2 设置布局
在activity_main.xml文件中,设置一个简单的布局。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:layout_centerInParent="true" />
</RelativeLayout>
2. 使用按钮
2.1 添加按钮
在布局文件中添加一个按钮。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_below="@id/textView"
android:layout_centerHorizontal="true" />
2.2 设置按钮点击事件
在MainActivity.java文件中,设置按钮点击事件。
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
3. 使用文本视图
3.1 添加文本视图
在布局文件中添加一个文本视图。
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text View"
android:layout_below="@id/button"
android:layout_centerHorizontal="true" />
3.2 设置文本视图内容
在MainActivity.java文件中,设置文本视图内容。
TextView textView2 = findViewById(R.id.textView2);
textView2.setText("This is a Text View.");
4. 使用编辑框
4.1 添加编辑框
在布局文件中添加一个编辑框。
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text"
android:layout_below="@id/textView2"
android:layout_margin="16dp" />
4.2 获取编辑框内容
在MainActivity.java文件中,获取编辑框内容。
EditText editText = findViewById(R.id.editText);
String text = editText.getText().toString();
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
5. 使用列表视图
5.1 添加列表视图
在布局文件中添加一个列表视图。
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:layout_margin="16dp" />
5.2 设置列表视图数据
在MainActivity.java文件中,设置列表视图数据。
ListView listView = findViewById(R.id.listView);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
6. 使用网格视图
6.1 添加网格视图
在布局文件中添加一个网格视图。
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:layout_below="@id/listView"
android:layout_margin="16dp" />
6.2 设置网格视图数据
在MainActivity.java文件中,设置网格视图数据。
GridView gridView = findViewById(R.id.gridView);
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
gridView.setAdapter(adapter);
7. 使用轮播图
7.1 添加轮播图
在布局文件中添加一个轮播图。
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@id/gridView"
android:layout_margin="16dp" />
7.2 设置轮播图数据
在MainActivity.java文件中,设置轮播图数据。
ViewPager viewPager = findViewById(R.id.viewPager);
String[] images = {"image1.jpg", "image2.jpg", "image3.jpg"};
MyAdapter adapter = new MyAdapter(this, images);
viewPager.setAdapter(adapter);
8. 使用地图
8.1 添加地图
在布局文件中添加一个地图。
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="@id/viewPager"
android:layout_margin="16dp" />
8.2 设置地图数据
在MainActivity.java文件中,设置地图数据。
MapFragment mapFragment = (MapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(37.7749, -122.4194)).title("San Francisco"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.7749, -122.4194), 10));
}
});
9. 使用通知
9.1 添加通知
在MainActivity.java文件中,添加通知。
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String channelId = "my_channel_id";
String channelName = "My Channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
notificationManager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle("Notification")
.setContentText("This is a notification")
.setSmallIcon(R.drawable.ic_notification)
.build();
notificationManager.notify(0, notification);
10. 使用数据库
10.1 创建数据库
在MainActivity.java文件中,创建数据库。
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AGE = "age";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
10.2 添加数据
在MainActivity.java文件中,添加数据。
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, "John");
values.put(COLUMN_AGE, 25);
db.insert(TABLE_NAME, null, values);
11. 使用网络请求
11.1 添加网络请求
在MainActivity.java文件中,添加网络请求。
String url = "https://jsonplaceholder.typicode.com/posts/1";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
12. 使用文件存储
12.1 创建文件
在MainActivity.java文件中,创建文件。
File file = new File(getFilesDir(), "myfile.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("Hello, Android!".getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
12.2 读取文件
在MainActivity.java文件中,读取文件。
File file = new File(getFilesDir(), "myfile.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(MainActivity.this, line, Toast.LENGTH_SHORT).show();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
13. 使用广播接收器
13.1 注册广播接收器
在AndroidManifest.xml文件中,注册广播接收器。
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.ACTION_MY_BROADCAST" />
</intent-filter>
</receiver>
13.2 创建广播接收器
在MyReceiver.java文件中,创建广播接收器。
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received broadcast!", Toast.LENGTH_SHORT).show();
}
}
13.3 发送广播
在MainActivity.java文件中,发送广播。
Intent intent = new Intent("com.example.ACTION_MY_BROADCAST");
sendBroadcast(intent);
14. 使用内容提供器
14.1 创建内容提供器
在AndroidManifest.xml文件中,创建内容提供器。
<provider android:name=".MyContentProvider"
android:authorities="com.example.myprovider"
android:exported="true" />
14.2 创建内容提供器类
在MyContentProvider.java文件中,创建内容提供器类。
public class MyContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.myprovider";
private static final String TABLE_NAME = "mytable";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = getReadableDatabase();
return db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
long newRowId = db.insert(TABLE_NAME, null, values);
return Uri.withAppendedPath(CONTENT_URI, String.valueOf(newRowId));
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
return db.delete(TABLE_NAME, selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
return db.update(TABLE_NAME, values, selection, selectionArgs);
}
}
14.3 使用内容提供器
在MainActivity.java文件中,使用内容提供器。
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.example.myprovider/mytable");
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
int age = cursor.getInt(cursor.getColumnIndexOrThrow("age"));
Toast.makeText(MainActivity.this, "Name: " + name + ", Age: " + age, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
15. 使用服务
15.1 创建服务
在AndroidManifest.xml文件中,创建服务。
<service android:name=".MyService" />
15.2 创建服务类
在MyService.java文件中,创建服务类。
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created!", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed!", Toast.LENGTH_SHORT).show();
}
}
15.3 启动服务
在MainActivity.java文件中,启动服务。
startService(new Intent(this, MyService.class));
15.4 停止服务
在MainActivity.java文件中,停止服务。
stopService(new Intent(this, MyService.class));
16. 使用广播接收器
16.1 注册广播接收器
在AndroidManifest.xml文件中,注册广播接收器。
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.example.ACTION_MY_BROADCAST" />
</intent-filter>
</receiver>
16.2 创建广播接收器
在MyReceiver.java文件中,创建广播接收器。
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received broadcast!", Toast.LENGTH_SHORT).show();
}
}
16.3 发送广播
在MainActivity.java文件中,发送广播。
Intent intent = new Intent("com.example.ACTION_MY_BROADCAST");
sendBroadcast(intent);
17. 使用内容提供器
17.1 创建内容提供器
在AndroidManifest.xml文件中,创建内容提供器。
<provider android:name=".MyContentProvider"
android:authorities="com.example.myprovider"
android:exported="true" />
17.2 创建内容提供器类
在MyContentProvider.java文件中,创建内容提供器类。
public class MyContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.myprovider";
private static final String TABLE_NAME = "mytable";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = getReadableDatabase();
return db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
long newRowId = db.insert(TABLE_NAME, null, values);
return Uri.withAppendedPath(CONTENT_URI, String.valueOf(newRowId));
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
return db.delete(TABLE_NAME, selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = getWritableDatabase();
return db.update(TABLE_NAME, values, selection, selectionArgs);
}
}
17.3 使用内容提供器
在MainActivity.java文件中,使用内容提供器。
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.example.myprovider/mytable");
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
int age = cursor.getInt(cursor.getColumnIndexOrThrow("age"));
Toast.makeText(MainActivity.this, "Name: " + name + ", Age: " + age, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
18. 使用服务
18.1 创建服务
在AndroidManifest.xml文件中,创建服务。
<service android:name=".MyService" />
18.2 创建服务类
在MyService.java文件中,创建服务类。
”`java public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created!", Toast.LENGTH_SHORT).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started!", Toast.LENGTH_SHORT).show
