Notepad学习笔记三

NoteEdit.java

package com.example.notepad;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

// TODO: Auto-generated Javadoc
/**
 * The Class Notepad.
 */
public class NoteEdit extends Activity {
    
    /** The et. */
    private EditText et;
    
    /** The Constant RECOGNIZER. */
    private static final int RECOGNIZER = 1001;     //Intent返回结果验证码
    
    /** The filename. */
    private String filename = "新建文档.txt";   //保存文本时默认文件名
    
    /** The my dialog edit text. */
    private EditText myDialogEditText;
    
    
    public static class LinedEditText extends EditText {
        private Rect mRect;
        private Paint mPaint;

        // This constructor is used by LayoutInflater
        public LinedEditText(Context context, AttributeSet attrs) {
            super(context, attrs);

            // Creates a Rect and a Paint object, and sets the style and color of the Paint object.
            mRect = new Rect();
            mPaint = new Paint();
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0x800000FF);
        }

        /**
         * This is called to draw the LinedEditText object
         * @param canvas The canvas on which the background is drawn.
         */
        @Override
        protected void onDraw(Canvas canvas) {

            // Gets the number of lines of text in the View.
            int count = getLineCount();

            // Gets the global Rect and Paint objects
            Rect r = mRect;
            Paint paint = mPaint;

            /*
             * Draws one line in the rectangle for every line of text in the EditText
             */
            for (int i = 0; i < count; i++) {

                // Gets the baseline coordinates for the current line of text
                int baseline = getLineBounds(i, r);

                /*
                 * Draws a line in the background from the left of the rectangle to the right,
                 * at a vertical position one dip below the baseline, using the "paint" object
                 * for details.
                 */
                canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
            }

            // Finishes up by calling the parent method
            super.onDraw(canvas);
        }
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_edit);
        et = (EditText) findViewById(R.id.EditText02);
        Intent intent = this.getIntent();
      //System.out.println(intent.getStringExtra("data"));
      et.setText(intent.getStringExtra("data"));
        
    }
    
//    public void onStart() {
//        Intent intent = this.getIntent();
//        System.out.println(intent.getStringExtra("data"));
//        et.setText(intent.getStringExtra("data"));
//    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    public void onResume() {        //重写onResume,防止程序stop后编辑内容丢失
        super.onResume();
        
        try {
            File file = new File("/mnt/sdcard/Notepad/temp.txt");       //读取临时文件,恢复上一次编辑内容
            RandomAccessFile stream = new RandomAccessFile(file, "rw");
            String s = stream.readLine();
            stream.close();
            et.setText(s);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /* (non-Javadoc)
     * @see android.app.Activity#onPause()
     */
    public void onPause() {     //编辑内容存入临时文件
        super.onPause();
        File file = new File("/mnt/sdcard/Notepad/temp.txt");
        String data = et.getText().toString();
        
        try {

            RandomAccessFile stream = new RandomAccessFile(file, "rw");
            stream.writeBytes(data);
            stream.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /* (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menuItemNew:
                creatNote();
                return true;
            case R.id.menuItemOpen:
                openNote();
                return true;
            case R.id.menuItemSave:
                saveNote();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Creat note.
     */
    private void creatNote() {
        et.setText("");
    }

    /**
     * Open note.
     */
    private void openNote() {
        Intent list = new Intent(this, OpenNote.class);
        startActivityForResult(list, RECOGNIZER);
    }

    /* (non-Javadoc)
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == RECOGNIZER && resultCode == RESULT_OK) {
            String text = data.getExtras().getString("data");
            et.setText(text);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Save note.
     */
    private void saveNote() {
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(
                R.layout.save_dialog, null);
        Builder builder = new AlertDialog.Builder(NoteEdit.this);
        builder.setView(textEntryView);
        myDialogEditText = (EditText) textEntryView
                .findViewById(R.id.myDialogEditText);
        myDialogEditText.setText(filename);
        builder.setTitle("保存");
        builder.setPositiveButton(R.string.str_alert_ok,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                            int which) {
                        // TODO Auto-generated method stub
                        File sdcardDir = Environment
                                .getExternalStorageDirectory();
                        String path = sdcardDir.getName()
                                + "/Notepad";
                        File f = new File(path);
                        File[] files = f.listFiles();
                        filename = myDialogEditText.getText().toString();
                        for (int i = 0; i < files.length; i++) {      //存在同名文件 
                            File file = files[i];
                            //Log.v("name", file.getName().toString());
                            if (file.getName().toString()
                                    .equals(filename)) {
                                new AlertDialog.Builder(NoteEdit.this).setTitle("文件名重复,请重新输入").setPositiveButton("OK", null).show();
                            }
                        }
                        String fileName = path
                                + java.io.File.separator
                                + myDialogEditText.getText()
                                        .toString();
                        java.io.BufferedWriter bw;
                        try {
                            bw = new java.io.BufferedWriter(
                                    new java.io.FileWriter(
                                            new java.io.File(fileName)));
                            String str = et.getText().toString();
                            bw.write(str, 0, str.length());
                            bw.newLine();
                            bw.close();
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                    }
                });
        builder.setNegativeButton(R.string.str_alert_cancel, null);
        builder.show();
        
    }
}

MyService.java

package com.example.notepad;

import java.text.SimpleDateFormat;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.example.notepad.Notepad;

public class MyService extends Service {

	private boolean flag = true;
	public static MyService service = null;
	private int i = 0;
	private Thread thread = null;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		service = this;
		thread = new Thread(new MyThread());
	}

	class MyThread implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (flag) {
				try {
					Thread.sleep(8000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				String s = "第" + (i++) + "次发送广播"+"\n";
				Log.i("send", s);
				Intent intent = new Intent(Notepad.INTENAL_ACTION_1);
				SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");      
				String   date   =   "当前系统时间:"+sDateFormat.format(new   java.util.Date());   
				intent.putExtra("message", s+date+"\n");
				// send Broadcast
				Notepad.getActivity().sendBroadcast(intent);
			}
		}

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		thread.start();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("send", "停止发送广播!");
		flag = false;
	}

	public static Service getService() {
		return service;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值