让我来为大家详细讲解“详解Android的四大应用程序组件”的攻略。
什么是四大应用程序组件
Android的四大应用程序组件包括:
- Activity(活动)
- Service(服务)
- ContentProvider(内容提供者)
- BroadcastReceiver(广播接收器)
这些组件结合起来,可以实现一个完整的Android应用。
Activity(活动)
Activity(活动)是Android系统中应用界面的核心组件,负责展示用户界面和接受用户输入。
可以理解为一个页面,在一个应用中可能会有多个Activity,通过activity之间的跳转实现应用的入口和不同功能的实现。
每个Activity有自己的生命周期,这个生命周期包括:OnCreate、OnStart、OnResume、OnPause、OnStop和OnDestroy方法。其中OnCreate、OnStart、OnResume和OnPause方法是必须实现的。
示例:以下是一个简单的计算器应用的MainActivity代码示例:
public class MainActivity extends AppCompatActivity{
EditText etValue1, etValue2;
Button btnAdd, btnSub, btn_mul, btn_div;
TextView tvResult;
int value1, value2;
int result = 0;
String operator = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etValue1 = (EditText) findViewById(R.id.et_value1);
etValue2 = (EditText) findViewById(R.id.et_value2);
btnAdd = (Button) findViewById(R.id.btn_add);
btnSub = (Button) findViewById(R.id.btn_sub);
btn_mul = (Button) findViewById(R.id.btn_mul);
btn_div = (Button) findViewById(R.id.btn_div);
tvResult = (TextView) findViewById(R.id.tv_result);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
operator = "+";
calculate();
}
});
btnSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
operator = "-";
calculate();
}
});
btn_mul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
operator = "*";
calculate();
}
});
btn_div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
operator = "/";
calculate();
}
});
}
private void calculate() {
value1 = Integer.parseInt(etValue1.getText().toString());
value2 = Integer.parseInt(etValue2.getText().toString());
switch (operator) {
case "+":
result = value1 + value2;
break;
case "-":
result = value1 - value2;
break;
case "*":
result = value1 * value2;
break;
case "/":
result = value1 / value2;
break;
}
tvResult.setText(String.valueOf(result));
}
}
Service(服务)
Service(服务)是在后台执行长期运行操作的组件,即使在用户退出应用或者锁屏的情况下,服务依然在后台运行。
示例:以下是一个简单的Android服务的示例代码:
public class MyService extends Service {
private Timer timer;
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.d("MyService", "Service is running...");
}
}, 0, 1000);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
Log.d("MyService", "Service is destroyed...");
}
}
ContentProvider(内容提供者)
ContentProvider(内容提供者)是Android提供的一种组件,用于在不同应用之间共享数据,类似于使用数据库操作数据。
示例:以下是一个简单的Android内容提供者的示例代码:
public class MyProvider extends ContentProvider {
private static final UriMatcher uriMatcher;
private static final int BOOK_DIR = 0;
private static final int BOOK_ITEM = 1;
private static final int CATEGORY_DIR = 2;
private static final int CATEGORY_ITEM = 3;
private static final String AUTHORITY = "com.example.myprovider";
private static MyDatabaseHelper dbHelper;
private static UriMatcher getUriMatcher() {
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "book", BOOK_DIR);
uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);
uriMatcher.addURI(AUTHORITY, "category", CATEGORY_DIR);
uriMatcher.addURI(AUTHORITY, "category/#", CATEGORY_ITEM);
return uriMatcher;
}
static {
uriMatcher = getUriMatcher();
}
@Override
public boolean onCreate() {
dbHelper = new MyDatabaseHelper(getContext(), "mydb", null, 1);
return true;
}
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
cursor = db.query("book", projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
cursor = db.query("book", projection, "id = ?", new String[]{bookId}, null, null, sortOrder);
break;
case CATEGORY_DIR:
cursor = db.query("category", projection, selection, selectionArgs, null, null, sortOrder);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
cursor = db.query("category", projection, "id = ?", new String[]{categoryId}, null, null, sortOrder);
break;
default:
break;
}
return cursor;
}
@Override
public String getType(@NonNull Uri uri) {
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.example.myprovider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.example.myprovider.book";
case CATEGORY_DIR:
return "vnd.android.cursor.dir/vnd.com.example.myprovider.category";
case CATEGORY_ITEM:
return "vnd.android.cursor.item/vnd.com.example.myprovider.category";
}
return null;
}
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Uri uriReturn = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
case BOOK_ITEM:
long newBookId = db.insert("book", null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/book" + newBookId);
break;
case CATEGORY_DIR:
case CATEGORY_ITEM:
long newCategoryId = db.insert("category", null, values);
uriReturn = Uri.parse("content://" + AUTHORITY + "/category" + newCategoryId);
break;
default:
break;
}
return uriReturn;
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int deletedRows = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
deletedRows = db.delete("book", selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
deletedRows = db.delete("book", "id = ?", new String[]{bookId});
break;
case CATEGORY_DIR:
deletedRows = db.delete("category", selection, selectionArgs);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
deletedRows = db.delete("category", "id = ?", new String[]{categoryId});
break;
default:
break;
}
return deletedRows;
}
@Override
public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int updatedRows = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
updatedRows = db.update("book", values, selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
updatedRows = db.update("book", values, "id = ?", new String[]{bookId});
break;
case CATEGORY_DIR:
updatedRows = db.update("category", values, selection, selectionArgs);
break;
case CATEGORY_ITEM:
String categoryId = uri.getPathSegments().get(1);
updatedRows = db.update("category", values, "id = ?", new String[]{categoryId});
break;
default:
break;
}
return updatedRows;
}
}
BroadcastReceiver(广播接收器)
BroadcastReceiver(广播接收器)是Android中用于接收广播消息的组件,可以在指定广播消息到达时执行相应的操作。
示例:以下是一个简单的Android广播接收器的示例代码:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
以上就是四大应用程序组件的详细攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解Android的四大应用程序组件 - Python技术站