打电话, 文件读取与写入 ,共享偏好 ,手机中的html页面操纵
启动Android内置的拨号程序------------打电话啦
btnDial.setOnClickListener(new Button.OnClickListener(){//为按钮添加点击事件的监听器
@Override
public void onClick(View v) {//重写onClick方法
Intent myIntent = new Intent(Intent.ACTION_DIAL);//创建Intent对象
Sample_3_5.this.startActivity(myIntent);//启动Android内置的拨号程序
}
});
----------------------------------------------------------------
文件读取与写入
FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);//获得FileOutputStream对象
FileInputStream fin = openFileInput(fileName);//获得FileInputStream对象
openFileOutput()方法的第一参数用于指定文件名称,不能包含路径分隔符“/” ,如果文件不存在,Android 会自动创建它。创建的文件保存在/data/data/<package name>/files目录,如: /data/data/cn.itcast.action/files/itcast.txt
如果希望文件被其他应用读和写,可以传入:
openFileOutput("itcast.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录
在程序中访问SDCard,你需要申请访问SDCard的权限。
在AndroidManifest.xml中加入访问SDCard的权限如下:
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//获取SDCard目录
File saveFile = new File(sdCardDir, “itcast.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("传智播客".getBytes());
outStream.close();
}
InputStream in = getResources().openRawResource(R.raw.test1); //从Resources中raw中的文件获取输入流
InputStream in = getResources().getAssets().open(fileName); //从Assets中的文件获取输入流
EncodingUtils.getString(buffer, ENCODING);
-------
public class DatabaseHelper extends SQLiteOpenHelper {
//类没有实例化,是不能用作父类构造器的参数,必须声明为静态
private static final String name = "itcast"; //数据库名称
private static final int version = 1; //数据库版本
public DatabaseHelper(Context context) {
//第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
super(context, name, null, version);
}
@Override public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS person");
onCreate(db);
}
}
DatabaseHelper databaseHelper = new DatabaseHelper(HelloActivity.this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});
db.close();
db.beginTransaction();//开始事务
try {
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});
db.execSQL("update person set name=? where personid=?", new Object[]{"传智", 1});
db.setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务,如果不调用此方法会回滚事务
} finally {
db.endTransaction();//由事务的标志决定是提交事务,还是回滚事务
}
db.close();
---------
Cursor cursor = db.rawQuery(“select * from person”, null);
while (cursor.moveToNext()) {
int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始
String name = cursor.getString(1);//获取第二列的值
int age = cursor.getInt(2);//获取第三列的值
}
cursor.close();
db.close();
或者:
int nameIndex = cursor.getColumnIndex("name"); //获取name列的索引
int levelIndex = cursor.getColumnIndex("level"); //获取level列的索引
for(cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()){ //遍历查询结果集,将数据提取出来
result = result + cursor.getString(nameIndex)+" ";
result = result + cursor.getInt(levelIndex)+" \n";
}
----------------------------
共享偏好对象---相当于java中的properties ,就是键值对
sp = getPreferences(MODE_PRIVATE); //获得SharedPreferences对象
String result = sp.getString(EDIT_TEXT_KEY, null);
if(result != null){ //如果获取的值不为空
etPre.setText(result); //EditText对象显示的内容设置为读取的数据
}
SharedPreferences.Editor editor = sp.edit(); //获得SharedPreferences的Editor对象
editor.putString(EDIT_TEXT_KEY, String.valueOf(etPre.getText())); //修改数据
editor.commit(); //必须调用该方法以提交修改
-------------------------------------------------------------------------------
手机中的html页面操纵
普通的带js的html页面
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function contactlist(jsons){
var table = document.getElementById("contactTable");
var arr = eval(jsons);
for(var i=0;i<arr.length;i++){
var jsonObj = arr[i];
var tr = table.insertRow(table.rows.length);
var td1 = tr.insertCell(0);
var td2 = tr.insertCell(1);
td2.align = "center";
var td3 = tr.insertCell(2);
td1.innerHTML = jsonObj.id;
td2.innerHTML = jsonObj.name;
td3.innerHTML = "<a href=\"javascript:webHandler.call('"+jsonObj.phone+"')\">"+jsonObj.phone+"</a>";
}
}
function pageInit(){
var content = "[{id:56,name:'老张',phone:'123456789'},{id:12,name:'老比',phone:'5556'}]";
contactlist(content);
}
</script>
<body onload="pageInit()">
<table width="100%" border="0" cellspacing="0" id="contactTable">
<tr bgcolor="#EEF7FF" style="font-size:18px;font-weight:bold;">
<td width="20%">编号</td>
<td align="center">姓名</td>
<td width="30%">电话</td>
</tr>
</table>
</body>
</html>
main.xml中有专门的webView来弄xml
<WebView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/webView" />
private Handler handler = new Handler();
webview = (WebView)this.findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportZoom(false);//设置缩放
webview.getSettings().setAppCacheEnabled(false);
webview.getSettings().setAllowFileAccess(true);
webview.addJavascriptInterface(new JSHandler(this,handler), "webHandler");
String url = "file:///android_asset/index.html";
webview.loadUrl(url);
处理js的类
public class JSHandler {
private Context context;
private WebView webView;
private Handler handler;
public JSHandler(Context context,Handler handler){
this.context = context;
this.handler = handler;
webView = (WebView)((Activity)context).findViewById(R.id.webView);
}
//在java中调用js的方法,并往js传递数据
public void show(){
handler.post(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:contactlist('"+query()+"')");
}
});
}
public void call(final String phone){
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "hhh", 0).show();
context.startActivity(new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone)));
}
});
}
public String query(){
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
JSONArray arr = new JSONArray();
try {
jsonObject.put("id", 56);
jsonObject.put("name", "老张");
jsonObject.put("phone", "5556");
jsonObject2.put("id", 89);
jsonObject2.put("name", "老放");
jsonObject2.put("phone", "5558");
arr.put(jsonObject);
arr.put(jsonObject2);
} catch (JSONException e) {
}
return arr.toString();
}
}
-------------------------------------------------------------
------------------------------------------------------------