权限声明
<?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"/>
<application
android: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">
<activity
android: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
<?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:layout_margin="10dp"
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="开始 : " />
<EditText
android:id="@+id/editText_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Please input start"
android:inputType="number" />
</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="结束 : " />
<EditText
android:id="@+id/editText_end"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Please input end"
android:inputType="number" />
</LinearLayout>
<TextView
android:id="@+id/num_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:text="已经计算出了0个质数" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:onClick="start"
android:text="开始计算" />
<Button
android:id="@+id/end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="end"
android:text="结束计算" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
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">
<ListView
android: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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher_round" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="计算完成"
android:textSize="20sp" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11:23" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android: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";
@Override
protected 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)+"
");
}
writer.close();
out.close();
//BufferedOutputStream writer=new BufferedOutputStream(new OutputStream(out));
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public 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菜单
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public 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);//自己维护通知的消失
//构建一个Intent
Intent resultIntent = new Intent(MainActivity.this,
MainActivity.class);
//封装一个Intent
PendingIntent 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>{
@Override
protected void onPreExecute() {
super.onPreExecute();
textView_result.setText("已经算出了0个质数");
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
//sendNotification(integer);
//initNotification();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
textView_result.setText("已经算出了"+values[0]+"个质数");
}
@Override
protected 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<>();
@Override
protected 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();
}
}
}