android.os.AsyncTask<String, Void, Integer>

本文详细介绍了AsyncTask的使用方法,包括其基本类型、四个步骤及如何在Android应用中正确使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

AsyncTask可以使得使用UI线程变的更容易更适当,它可以在后台运行一些操作然后在UI上展现,不用操作具体的线程和handlers
一个 asynchronous task包括三种基本类型(调用参数,进度和结果),和四个步骤(调用开始,在后台运行,处理进度,结束)
), and most often will override a second one (onPostExecute(Result).)

 

使用方法描述
Asynchronous Task必须是作为一个子类来使用,
task实例必须在UI线程创建
execute(Params...)必须在UI线程调用
不要手工调用onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...)。
task只可以execute一次,执行多次就报异常

一个例子
类的定义
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
类的使用
new DownloadFilesTask().execute(url1, url2, url3);

 

三种基本类型的说明
Params, 传给task的参数的类型
Progress, 表示进度单位的类型
Result, 返回类型
不是所有的task都需要定义类型,如果没有则使用void,如下所示
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 
四个步骤的说明
onPreExecute():
在task被执行之后,立刻调用

doInBackground(Params...):
onPreExecute执行完毕后,执行该方法,参数传到了这个方法中,执行完毕后必须返回一个值,还可以使用 publishProgress(Progress...) 发布进度到onProgressUpdate(Progress...),便于更新进度

onProgressUpdate(Progress...):
publishProgress(Progress...)被调用后,就执行该方法,显示进度信息
通常是显示一个进度条,或在text域里显示日志信息

onPostExecute(Result)
当doInBackground(Params...)执行完毕后即执行该方法

手机实名制 OCR功能中的实例
例子一
定义
class OcrTask extends AsyncTask<String, Void, OcrMessage>
{
 @Override
 protected OcrMessage doInBackground(String... arg0)
 {
  ApplyService service  = new ApplyService(getApplicationContext());
  return service.ocrTest(save_file_path);
 }
 @Override
   protected void onPostExecute(OcrMessage result)
   {
    returnImageScan(result);
   }
}

调用
OcrTask ocr = new OcrTask();
ocr.execute(save_file_path);


例子二
保存图片任务,参数是byte数组,是图片对应的byte数组
class SavePhotoTask extends AsyncTask<byte[], Void, Integer>
{
      String picname;
      @Override
      protected Integer doInBackground(byte[]... datas)
      {
   byte[] data = datas[0];
   Bitmap bitmap;
   BitmapFactory.Options ops2 = new BitmapFactory.Options();
   ops2.inSampleSize = 1;
   bitmap = BitmapFactory.decodeByteArray(data,0, data.length,ops2);
  
   try {
   FileOutputStream fos = OcrCameraActivity.this.openFileOutput("output.jpg",Activity.MODE_WORLD_READABLE);
   bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
   fos.flush();
   fos.close();
   save_file_path = "output.jpg";
  }catch (Exception e) {
   e.printStackTrace();
  }
  return 0;
      }
     
   @Override
   protected void onPostExecute(Integer result)
   {
    call_OCR();
   }
}

调用
SavePhotoTask savePhotoTask = new SavePhotoTask();
savePhotoTask.execute(data);

package com.hmongsoft.merchant.Module.dataSource.onLine.V20230707; import android.os.AsyncTask; import com.hmongsoft.merchant.Base.Interface.ActionCallbackValue; import com.hmongsoft.merchant.Base.config.SysConfig; import java.io.IOException; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; /** * 校验商铺名称是否存在 */ public class JudgeMerchantIsExist { public JudgeMerchantIsExist(String merchantName, ActionCallbackValue<String,Boolean> actionCallback) { SignInTask signInTask=new SignInTask(merchantName,actionCallback); signInTask.execute(); } private static class SignInTask extends AsyncTask<String,Integer,Boolean>{ private String merchantName; private ActionCallbackValue<String,Boolean> actionCallback; private String requestResult; public SignInTask(String merchantName, ActionCallbackValue<String,Boolean> actionCallback) { this.merchantName =merchantName; this.actionCallback=actionCallback; } //异步前(UI) @Override protected void onPreExecute() { super.onPreExecute(); } //异步中(非UI) @Override protected Boolean doInBackground(String... strings) { OkHttpClient client = new OkHttpClient().newBuilder().build(); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("merchantName",merchantName) .build(); Request request = new Request.Builder() .url(SysConfig.MerchantPORT+"/MerchantController/judgeMerchantNameIsExist") .method("POST", body) .build(); try { requestResult = client.newCall(request).execute().body().string(); if (requestResult.equals("true")){ return true; }else { return false; } } catch (IOException e) { e.printStackTrace(); return false; } } //异步后(UI) @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); actionCallback.callback("result",aBoolean); } } } 这段代码的SignInTask已经被弃用,请帮换一个写法
07-08
实验四的界面是图书查询界面Ss.java类代码: import static com.example.myapplication.R.id.tt_hg; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Ss extends AppCompatActivity { private EditText editId; private EditText editName; private EditText editAuthor; private static final int item1 = Menu.FIRST; private static final int item2 = Menu.FIRST + 1; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); EditText syqt = findViewById(R.id.edit_id); syqt.setTextSize(Integer.valueOf(size)); EditText cxqt = findViewById(R.id.edit_name); cxqt.setTextSize(Integer.valueOf(size)); EditText szqt = findViewById(R.id.edit_author); szqt.setTextSize(Integer.valueOf(size)); RadioButton dfqt = findViewById(tt_hg); dfqt.setTextSize(Integer.valueOf(size)); RadioButton dft = findViewById(R.id.tt_hu); dft.setTextSize(Integer.valueOf(size)); Button dfttd = findViewById(R.id.btn_ff); dfttd.setTextSize(Integer.valueOf(size)); Button dftqq = findViewById(R.id.btn_clar); dftqq.setTextSize(Integer.valueOf(size)); Button dftww = findViewById(R.id.btn_back); dftww.setTextSize(Integer.valueOf(size)); Button dftwwl = findViewById(R.id.ff_id1); dftwwl.setTextSize(Integer.valueOf(size)); Button dftwws = findViewById(R.id.ff_id2); dftwws.setTextSize(Integer.valueOf(size)); Button dftwwt = findViewById(R.id.ff_id3); dftwwt.setTextSize(Integer.valueOf(size)); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToEditText(editId, size, color); applyStyleToEditText(editName, size, color); applyStyleToEditText(editAuthor, size, color); } private void applyStyleToEditText(EditText btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ss); // 初始化 EditText editId = findViewById(R.id.edit_id); editName = findViewById(R.id.edit_name); editAuthor = findViewById(R.id.edit_author);//通过ID绑定视图对象 RadioButton ttHg = findViewById(R.id.tt_hg); RadioButton ttHu = findViewById(R.id.tt_hu); Button btnFf = findViewById(R.id.btn_ff); LinearLayout ll = findViewById(R.id.table_layout); registerForContextMenu(ll); btnFf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在此处编写查询逻辑(示例:Toast提示) // Toast.makeText(Ss.this, "查询按钮被点击,执行查询操作", Toast.LENGTH_SHORT).show(); } }); // 1清空 - 属性事件响应(XML 按钮需添加 android:onClick="clearByAttribute") // 2清空 - 内部匿名类事件响应 findViewById(R.id.ff_id1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearFields(); } }); // 3清空 - 监听器接口实现类事件响应 findViewById(R.id.ff_id2).setOnClickListener(new MyClickListener()); // 4清空 - 外部监听器接口实现类事件响应 findViewById(R.id.ff_id3).setOnClickListener(new ExternalClickListener(this)); Button btnBack = findViewById(R.id.btn_back); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Ss.this, Sy.class); startActivity(intent); finish(); } }); } // 1清空对应的属性事件响应方法 public void clearByAttribute(View view) { clearFields(); }//当用户点击按钮就会被执行 // 清空文本框的公共方法 public void clearFields() { if (editId != null) editId.setText(""); if (editName != null) editName.setText(""); if (editAuthor != null) editAuthor.setText(""); } // 内部监听器接口实现类(3清空) private class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { clearFields(); } } // 外部监听器接口实现类(4清空) @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) { menu.add(0, 1, 0, "删除"); menu.add(0, 2, 0, "修改"); super.onCreateContextMenu(menu, view, info); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getItemId() == 1) { Toast.makeText(this, "您点击了删除", Toast.LENGTH_LONG).show(); } else if (item.getItemId() == 2) { Toast.makeText(this, "您点击了修改", Toast.LENGTH_LONG).show(); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, item1, 0, "关于"); menu.add(0, item2, 0, "退出"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case item1: Toast.makeText(Ss.this, "姓名:骆树涛。学号:2404224132", Toast.LENGTH_SHORT).show(); break; case item2: this.finish(); break; } return true; } } 图书查询界面的ss.XML布局文件代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书编号" android:textSize="20dp"/> <EditText android:id="@+id/edit_id" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书名称" android:textSize="20dp"/> <EditText android:id="@+id/edit_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书作者" android:textSize="20dp"/> <EditText android:id="@+id/edit_author" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="中文" android:textSize="20dp"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="外文" android:textSize="20dp"/> </RadioGroup> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询" android:textSize="20dp"/> <Button android:id="@+id/btn_clar" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="清空" android:textSize="20dp" android:onClick="clearByAttribute"/> <Button android:id="@+id/btn_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回" android:textSize="20dp"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:id="@+id/ff_id1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清空" android:textSize="20dp"/> <Button android:id="@+id/ff_id2" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="清空" android:textSize="20dp" /> <Button android:id="@+id/ff_id3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清空" android:textSize="20dp"/> </LinearLayout> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="*"> <TableRow> <TextView android:text="图书编号" android:textSize="15dp"/> <TextView android:text="图书名称" android:textSize="15dp"/> <TextView android:text="图书作者" android:textSize="15dp"/> <TextView android:text="馆藏地点" android:textSize="15dp"/> </TableRow> <TableRow android:id="@+id/table_layout"> <TextView android:text="1001" android:textSize="15dp"/> <TextView android:text="Android" android:textSize="15dp"/> <TextView android:text="张三" android:textSize="15dp"/> <TextView android:text="5-423" android:textSize="15dp"/> </TableRow> <TableRow> <TextView android:text="查询结果1条" android:textSize="15dp" android:layout_span="4" android:layout_gravity="center"/> </TableRow> </TableLayout> </LinearLayout> 实验六的代码如下 新增Xz.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Xz extends AppCompatActivity { private EditText editBookId; private EditText editBookName; private EditText editBookAuthor; private EditText editBookLocation; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); EditText syq = findViewById(R.id.edit_book_id); syq.setTextSize(Integer.valueOf(size)); EditText cxq = findViewById(R.id.edit_book_name); cxq.setTextSize(Integer.valueOf(size)); EditText szq = findViewById(R.id.edit_book_author); szq.setTextSize(Integer.valueOf(size)); EditText dfq = findViewById(R.id.edit_book_location); dfq.setTextSize(Integer.valueOf(size)); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToEditText(editBookId, size, color); applyStyleToEditText(editBookName, size, color); applyStyleToEditText(editBookAuthor, size, color); applyStyleToEditText(editBookLocation, size, color); } private void applyStyleToEditText(EditText btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.xz); editBookId = findViewById(R.id.edit_book_id); editBookName = findViewById(R.id.edit_book_name); editBookAuthor = findViewById(R.id.edit_book_author); editBookLocation = findViewById(R.id.edit_book_location); Button btnAddBook = findViewById(R.id.btn_add_book); btnAddBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String bookId = editBookId.getText().toString(); String bookName = editBookName.getText().toString(); String bookAuthor = editBookAuthor.getText().toString(); String bookLocation = editBookLocation.getText().toString(); Intent intent = new Intent(Xz.this, Xq.class); intent.putExtra("bookId", bookId); intent.putExtra("bookName", bookName); intent.putExtra("bookAuthor", bookAuthor); intent.putExtra("bookLocation", bookLocation); startActivity(intent); } }); } } 新增的xz.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书编号" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_id" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书名称" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_name" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="图书作者" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_author" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="馆藏地点" android:textSize="20dp"/> <EditText android:id="@+id/edit_book_location" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> <Button android:id="@+id/btn_add_book" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增" android:textSize="20dp" android:layout_gravity="center"/> </LinearLayout> 详情Xq.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Xq extends AppCompatActivity { private static final int ITEM_HOME = Menu.FIRST; public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); TextView syqw = findViewById(R.id.tv_book_id); syqw.setTextSize(Integer.valueOf(size)); TextView cxqw = findViewById(R.id.tv_book_name); cxqw.setTextSize(Integer.valueOf(size)); TextView szqw = findViewById(R.id.tv_book_author); szqw.setTextSize(Integer.valueOf(size)); TextView dfqw = findViewById(R.id.tv_book_location); dfqw.setTextSize(Integer.valueOf(size)); super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.xq); TextView tvBookId = findViewById(R.id.tv_book_id); TextView tvBookName = findViewById(R.id.tv_book_name); TextView tvBookAuthor = findViewById(R.id.tv_book_author); TextView tvBookLocation = findViewById(R.id.tv_book_location); Intent intent = getIntent(); String bookId = intent.getStringExtra("bookId"); String bookName = intent.getStringExtra("bookName"); String bookAuthor = intent.getStringExtra("bookAuthor"); String bookLocation = intent.getStringExtra("bookLocation"); tvBookId.setText("图书编号:" + bookId); tvBookName.setText("图书名称:" + bookName); tvBookAuthor.setText("图书作者:" + bookAuthor); tvBookLocation.setText("馆藏地点:" + bookLocation); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, ITEM_HOME, 0, "首页"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case ITEM_HOME: Intent intent = new Intent(Xq.this, Sy.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } } 详情的xq.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/tv_book_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_author" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> <TextView android:id="@+id/tv_book_location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> </LinearLayout> 首页Sy.JAVA类代码 import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceManager; public class Sy extends AppCompatActivity { private Button btnAdd; private Button btnSearch; private Button btnSetting; private static final int item1 = Menu.FIRST; private static final int item2 = Menu.FIRST + 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sy); btnAdd = findViewById(R.id.btn_add); btnSearch = findViewById(R.id.btn_search); btnSetting = findViewById(R.id.btn_setting); btnSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, SettingsActivity.class); startActivity(intent); } }); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, Xz.class); startActivity(intent); } }); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Sy.this, Ss.class); startActivity(intent); } }); } public void onResume(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String size = sp.getString("font_size","25"); Button sy = findViewById(R.id.btn_add); sy.setTextSize(Integer.valueOf(size)); Button cx = findViewById(R.id.btn_search); cx.setTextSize(Integer.valueOf(size)); Button sz = findViewById(R.id.btn_setting); sz.setTextSize(Integer.valueOf(size)); String bg = sp.getString("bg","c"); int pic_id = this.getResources().getIdentifier(bg,"drawable","com.example.myapplication"); LinearLayout bg_b = findViewById(R.id.bg_d); bg_b.setBackgroundResource(pic_id); updateUI(); super.onResume(); } private void updateUI() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String fontSize = sp.getString("font_size", "15"); int size = Integer.parseInt(fontSize); String textColor = sp.getString("text_color", "#FF000000"); int color = Color.parseColor(textColor); applyStyleToButton(btnAdd, size, color); applyStyleToButton(btnSearch, size, color); applyStyleToButton(btnSetting, size, color); } private void applyStyleToButton(Button btn, int size, int color) { btn.setTextSize(size); btn.setTextColor(color); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, item1, 0, "关于"); menu.add(0, item2, 0, "退出"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case item1: Toast.makeText(Sy.this, "姓名:骆树涛。学号:2404224132", Toast.LENGTH_SHORT).show(); break; case item2: finishAffinity(); break; } return true; } } 首页的sy.XML布局文件代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/bg_d" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/btn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增" android:textSize="15dp"/> <Button android:id="@+id/btn_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询" android:textSize="15dp"/> <Button android:id="@+id/btn_setting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设置" android:textSize="15dp"/> </LinearLayout> SettingsActivity.Java设置类代码: import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.PreferenceFragmentCompat; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.se); // 加载容器布局 // 加载PreferenceFragment到Activity中 getSupportFragmentManager() .beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } // 静态内部类:管理设置项的Fragment public static class SettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { // 从XML文件加载设置项(需创建res/xml/settings.xml) setPreferencesFromResource(R.xml.settings, rootKey); } } } Se.XML布局文件代码: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/content" android:layout_width="match_parent" android:layout_height="match_parent"/> arry.XML的valuse代码: <?xml version="1.0" encoding="utf-8"?> <resources> <!-- 颜色选项 --> <string-array name="color_entries"> <item>黑色</item> <item>红色</item> <item>黄色</item> <item>蓝色</item> </string-array> <string-array name="color_values"> <item>#FF000000</item> <!-- 黑色 --> <item>#FFFF0000</item> <!-- 红色 --> <item>#FFFFFF00</item> <!-- 黄色 --> <item>#FF0000FF</item> <!-- 蓝色 --> </string-array> <!-- 背景图片选项(需在drawable目录准备对应图片) --> <string-array name="bg"> <item>科技</item> <item>书籍</item> </string-array> <string-array name="bg_hhg"> <item>a</item> <item>b</item> <item>c</item> </string-array> </resources> sring.XML的xml代码: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 字号设置 --> <EditTextPreference android:key="font_size" android:title="字号设置" android:summary="输入文字大小" android:defaultValue="15" android:inputType="number"/> <!-- 颜色选择 --> <ListPreference android:key="text_color" android:title="文字颜色" android:summary="选择文字显示颜色" android:defaultValue="black" android:entries="@array/color_entries" android:entryValues="@array/color_values"/> <!-- 背景图片选择 --> <ListPreference android:key="bg" android:title="首页背景" android:summary="选择首页背景图片" android:entries="@array/bg" android:entryValues="@array/bg_hhg"/> </PreferenceScreen> AndroidManifest.xml代码 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.MyApplication" tools:targetApi="31"> <meta-data android:name="com.google.android.actions" android:resource="@layout/sy" /> <activity android:name=".Sy" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Xz" /> <activity android:name=".Xq" /> <activity android:name=".Ss" /> <activity android:name=".Cada" /> <!-- 新增:注册设置活动 --> <activity android:name=".SettingsActivity" android:label="设置" android:theme="@style/Theme.AppCompat.Light.DarkActionBar" /> <!-- <activity--> <!-- android:name=".SettingsActivity"--> <!-- android:exported="true"--> <!-- android:label="@string/app_name"--> <!-- android:theme="@style/Theme.MyApplication"/>--> <!-- <intent-filter>--> <!-- <action android:name="android.intent.action.MAIN" />--> <!-- <category android:name="android.intent.category.LAUNCHER" />--> <!-- </intent-filter>--> <!-- </activity>--> </application> </manifest> 内部存储(Internal Storage)的Context中提供了相应的函数对文件进行操作, 实验7:基于文件存储的数据读写 在实验6的基础上,实现基于Android系统文件存储的数据存储功能,具体要求如下: (1)增加一个励志标题添加功能。在首页增加“设置标题”按钮,点击后进入励志标题编辑界面,励志标题文字保存在内部存储的文件中,文件名以开发者自己的姓名拼音命名,例如“zhangsan.txt”。用户打开软件后,标题栏的标题文字从内部文件中读取并显示。 (2)修改图书新增功能。点击“新增”按钮后,用户输入的图书数据存储在外部文件中,文件名以开发者自己的姓名拼音命名,例如“zhangsan.txt”。数据新增完毕后,自动跳到图书查询页面。 (3) 修改图书查询页面。打开图书查询界面后,界面中的那条图书信息从外部文件中读取,并显示在相应的位置。 以上内容的全部代码
最新发布
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值