exam02-02
權限聲明
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.exam02_2"><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activityandroid:name=".HistoryActivity"android:label="計算結果"></activity><activity android:name=".MainActivity"android:label="質數計算"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>布局文件
activity_main.xml
activity_history.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".HistoryActivity"><ListViewandroid:id="@+id/listview"android:layout_width="0dp"android:layout_height="0dp"android:layout_marginStart="8dp"android:layout_marginLeft="8dp"android:layout_marginTop="8dp"android:layout_marginEnd="8dp"android:layout_marginRight="8dp"android:layout_marginBottom="8dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>notification_layout.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="60dp"android:orientation="horizontal"><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@mipmap/ic_launcher_round" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="計算完成"android:textSize="20sp" /><TextViewandroid:id="@+id/time"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="11:23" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:id="@+id/count"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="end"android:text="共有10個質數" /></LinearLayout></LinearLayout></LinearLayout>MainActivity.xml
package com.example.exam02_2;import android.Manifest; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.RemoteViews; import android.widget.TextView;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date;public class MainActivity extends AppCompatActivity {private EditText editText_start;private EditText editText_end;private TextView textView_result;private boolean flag;ArrayList<Integer> history = new ArrayList<Integer>();private final static String myChannel = "lys";public final static String filename = "historyList";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);}}public void init(){editText_end = findViewById(R.id.editText_end);editText_start = findViewById(R.id.editText_start);textView_result = findViewById(R.id.num_result);flag = true;}public void start(View v){int begin = Integer.parseInt(editText_start.getText().toString());int end = Integer.parseInt(editText_end.getText().toString());flag = true;new MyAsyncTask().execute(begin,end);}public void end(View v){flag =false;}public void save(){try{File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);File file = new File(path,filename);FileOutputStream out = new FileOutputStream(file,true);OutputStreamWriter writer = new OutputStreamWriter(out);for(int i=0;i<history.size();i++){writer.write("第"+(i+1)+"個質數是:"+history.get(i)+"\r\n");}writer.close();out.close();//BufferedOutputStream writer=new BufferedOutputStream(new OutputStream(out));}catch (Exception e){e.printStackTrace();}}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);if(requestCode == 0){if(grantResults[0]==PackageManager.PERMISSION_GRANTED){}else{ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);}}}//顯示History菜單@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.main_menu,menu);return super.onCreateOptionsMenu(menu);}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()){case R.id.action_history:// saveHistory();save();Intent intent = new Intent(MainActivity.this, HistoryActivity.class);//intent.putStringArrayListExtra("history",res_list);startActivity(intent);return true;}return super.onOptionsItemSelected(item);}public void sendNotification(Integer integer){//NotificationManager管理通知NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {//Builder構造器創建Notification對象//NotificationCompat.Builder builder = new NotificationCompat.Builder(this);NotificationChannel channel = new NotificationChannel(myChannel,"my result notification",NotificationManager.IMPORTANCE_DEFAULT);manager.createNotificationChannel(channel);NotificationCompat.Builder builder = new NotificationCompat.Builder(this,myChannel);RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.notification_layout);remoteViews.setTextViewText(R.id.time,new SimpleDateFormat("HH:mm").format(System.currentTimeMillis()));remoteViews.setTextViewText(R.id.count,"共有"+integer+"個質數");builder.setContent(remoteViews);//延遲意圖 // Intent intent = new Intent(this,MainActivity.class); // PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);//builder.setContentIntent(pendingIntent);manager.notify(100,builder.build());}}public void initNotification(){Bitmap btm = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this).setContentTitle("計算完成").setContentText("共有"+history.size()+"個質數");mBuilder.setTicker("New message");//第一次提示消息的時候顯示在通知欄上mBuilder.setNumber(12);mBuilder.setLargeIcon(btm);mBuilder.setAutoCancel(true);//自己維護通知的消失//構建一個IntentIntent resultIntent = new Intent(MainActivity.this,MainActivity.class);//封裝一個IntentPendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);// 設置通知主題的意圖mBuilder.setContentIntent(resultPendingIntent);//獲取通知管理器對象NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(0, mBuilder.build());}class MyAsyncTask extends AsyncTask<Integer,Integer,Integer>{@Overrideprotected void onPreExecute() {super.onPreExecute();textView_result.setText("已經算出了0個質數");}@Overrideprotected void onPostExecute(Integer integer) {super.onPostExecute(integer);//sendNotification(integer);//initNotification();}@Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);textView_result.setText("已經算出了"+values[0]+"個質數");}@Overrideprotected Integer doInBackground(Integer... integers) {for (int i=integers[0]; flag&&i<=integers[1]; i++) {boolean isPrime=true;for (int j=2; j<=Math.sqrt(i); j++) {if(i%j==0) {isPrime=false;break;}try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}if (isPrime){//i是素數history.add(i);}publishProgress(history.size());}initNotification();return history.size();}} }HistoryActivity.xml
package com.example.exam02_2;import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List;public class HistoryActivity extends AppCompatActivity {private ListView listView;private List<String> historyList = new ArrayList<>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_history);readFile();listView = findViewById(R.id.listview);ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,historyList);listView.setAdapter(adapter);}public void readFile(){File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);File file = new File(path,MainActivity.filename);try {FileInputStream fis = new FileInputStream(file);InputStreamReader reader = new InputStreamReader(fis);BufferedReader br = new BufferedReader(reader);String line = "";while((line=br.readLine())!=null) {historyList.add(line.trim());}br.close();reader.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}catch (Exception e){e.printStackTrace();}} }轉載于:https://www.cnblogs.com/lyszyl/p/10821736.html
總結
- 上一篇: 数据结构之B树与B+树
- 下一篇: Rocketmq基于docker部署并在