杰言杰语

以中有足乐者,不知口体之奉不若人也.


  • 首页

  • 分类

  • 关于

  • 归档

  • 标签

  • 搜索

7.安卓基础之activity生命周期&receiver广播接收者

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. Activity

Android中的第一个核心的组件,每次创建一个工程,都会创建一个默认的MainActivity.

  • onCreate 在创建对象的时候调用
    Activity启动后第一个被调用的函数,常用来进行Activity的初始化,例如创建View/绑定数据或恢复信息等.

  • onDestory 在对象销毁的时候调用
    在Activity被终止前,即进入非活动状态前,该函数被调用.

  • onStart 在界面可见的时候被调用
    当Activity显示在屏幕时,该函数被调用.

  • onStop 在界面不可见的时候被调用
    当Activity进入停止状态时,该函数被调用.

  • onPause 当界面处于可见,但是又失去焦点这个阶段的时候会被调用
    当Activity进入暂停状态时,该函数被调用.一般用来保持持久的数据或释放占用的资源.

  • onReumse 当界面处于可见到获得焦点这段时间被调用
    当Activity被终止时,即进入非活动状态时,该函数被调用.

1.1 生命周期之记事本的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainActivity extends AppCompatActivity {
private EditText ed_content;
SharedPreferences sp;
//创建时调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_content = (EditText) findViewById(R.id.ed_content);
sp = getSharedPreferences("config",0);
String v1 = sp.getString("content","");
ed_content.setText(v1);
}
//当销毁时调用
@Override
protected void onDestroy() {
super.onDestroy();
String content = ed_content.getText().toString().trim();
SharedPreferences.Editor edit = sp.edit();
edit.putString("content",content);
edit.commit();
Toast.makeText(this,"已默认保存!",0).show();
}
}

1.2 生命周期之格斗小游戏的应用

  • AndroidManifest.xml
    如果配置了这个属性,当我们横竖屏切换的时候会直接调用onCreate方法中的onConfigurationChanged方法,而不会重新执行onCreate方法,那当然如果不配置这个属性的话就会重新调用onCreate方法了.
    1
    <activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize">

默认的情况下,一个activity声明周期在横竖屏切换的时候,会销毁当前的activity,然后去重新创建一个activity.所以在当前游戏中,会影响到用户的感受.

2. Activity的启动模式

Task : 任务,维护记录了当前应用的内存空间中,有哪些组件在运行着.
Stack : 栈,栈的特点(后进先出),队列(先进先出)

  • 启动模式(lauchMode)有四种 :
    • standard : 标准的模式,也是默认模式.
      每次收到intent,那么就会新创建activity的实例出来,放到任务栈中.
    • singleTop : 单一顶部模式
      如果发现当前的任务栈中的栈顶是当前activity实例,那么就直接使用当前的activity实例,不再创建.(源生的mms编辑短信activity启动模式是singleTop,为了提高用户感受,可以很好的提示用户之前的短信还没有编辑完)
    • singleTask : 单一任务模式
      表示当前的activity只会在当前任务栈中创建一个实例.如果再次去尝试启动之前的activity时候,当前的activity不是处于任务栈的栈顶,会清空当前处于activity之上的activity.(如果一个activity启动的时候,占用的CPU资源非常多,非常耗内存.而手机中的内存又非常珍贵,那么这个时候就建议使用activity的启动模式设置为:singleTask).
1
android:launchMode="singleTask"
  • singleInstance : 单一实例模式
    如果某个activity的启动模式设置为singleInstance,那么在整个android手机就只会有一个实例了.(对于一些整个系统中,永远都只存在一个同样的界面的activity就会声明使用这种启动模式)

3. broadcastReceiver(广播接收者)

  • 具体实现步骤 :
    • 写个类,继承BroadcastReceiver的类,那么就等价于拥有了一个收音机
    • 到清单manifest文件中进行装电池,配置的问题
    • 调节频道,设置接受广播的类型

在整个android系统中,有很多系统已经定义好的广播事件,这些事件是在系统启动,运行的时候发出的.

例如 : sd卡被挂载 / 开机完成 / 电话拨出 / 应用被安装/被卸载

3.1 编写开机完成广播接收者

  • AndroidManifest.xml
    • 先开启接收广播权限
1
2
3
4
5
6
7
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.itheima.bootcompletion.BootCompletionReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
1
2
3
4
5
6
7
8
9
10
11
12
public class BootCompletionReceiver extends BroadcastReceiver {
// 监听开机启动完成
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("开机完成了 .... : " + action);
}
}

3.2 IP拨号器之广播

  • AndroidManifest.xml
1
2
3
4
5
6
7
8
<!--先声明广播权限,允许一个程序接收到 ACTION_BOOT_COMPLETED广播在系统完成启动--><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!--然后说明那个广播器,接收什么类型的广播-->
<receiver android:name=".OutPhone">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
  • MainActivity.java的代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MainActivity extends AppCompatActivity {
private EditText ed_phone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_phone = (EditText)findViewById(R.id.ed_prefix);
}
public void save(View v){
String prefix = ed_phone.getText().toString().trim();
if(TextUtils.isEmpty(prefix)){
Toast.makeText(this,"ip号码不能为空",0).show();
return;
}
SharedPreferences sp = getSharedPreferences("config",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("prefix",prefix);
editor.commit();
Toast.makeText(this,"IP前缀保存成功",0).show();
}
}
  • OutPhone.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class OutPhone extends BroadcastReceiver {
//alt+enter补全代码
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sp = context.getSharedPreferences("config",0);
String ipdata = sp.getString("prefix","");
if(ipdata.startsWith("0")){
//说明是长途电话
setResultData(ipdata);
}
}
}

3.2 对应用内的数据进行统计之广播

  • AndroidManifest.xml
1
2
3
4
5
6
7
<receiver android:name="com.javami.bigdatacollect.AppStatusReceiver">
<intent-filter >
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
  • AppStatusReceiver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class AppStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println(action);
if("android.intent.action.PACKAGE_ADDED".equals(action)){
System.out.println("应用安装了: " + intent.getData());
}else if("android.intent.action.PACKAGE_REMOVED".equals(action)){
System.out.println("应用卸载了 " + intent.getData());
}
}
}

4. 自定义广播

4.1 无序广播

1
2
3
4
5
6
public void sendBroadcast(View v){
System.out.println("发出自定义的广播了");
Intent intent = new Intent();
intent.setAction("com.javami.honey");
sendBroadcast(intent); // 发送一个广播出去
}

4.2 接收自定义广播

  • AndroidManifest.xml
1
2
3
4
5
<receiver android:name=".MyBroadCastReciver">
<intent-filter>
<action android:name="com.javami.honey"></action>
</intent-filter>
</receiver>
  • MyBroadCastReciver.java
1
2
3
4
5
6
public class MyBroadCastReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("收到了广播 : " + intent.getAction());
}

4.2 有序广播

  • AndroidManifest.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<receiver android:name=".ShengZhang">
<!--数字越大,优先级别越高-->
<intent-filter android:priority="1000">
<!--隐式调用广播-->
<action android:name="com.javmai.send.Money"></action>
</intent-filter>
</receiver>
<receiver android:name=".Baixing">
<!--数字越大,优先级别越高-->
<intent-filter android:priority="5000">
<!--隐式调用指定的广播-->
<action android:name="com.javmai.send.Money"></action>
</intent-filter>
</receiver>
  • MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void sendMarshroom(View v){
Intent intent = new Intent();
// intent : 设置一个意图行动
intent.setAction("com.javmai.send.Money");
// intent : 意图对象
// receiverPermission : 接收广播的 组件需要什么样的权限
// resultReceiver : 广播事件的最终 接收者
// scheduler : 调度器
// initialCode : 发送广播时的初始码
// initialData : 广播 发出的 原始数据 -- 未被 修改过的原始数据
// initialExtras : 广播发出时的一些额外的数据
sendOrderedBroadcast(intent,null,new FinalResultReveiver(),null,1,"每人1000元",null);
}
  • ShengZhang.java and BaiXing.java and FinalResultReceiver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ShengZhang extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String money = getResultData();
setResultData("500元");
System.out.print("收到"+money);
}
public class Baixing extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String money = getResultData();
System.out.print("收到"+money);
}
}
public class FinalResultReveiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//纪委部
String money = getResultData();
System.out.print("实际百姓只收到"+money);
}

有序广播和无序广播的区别

有序广播可以在特定的接收者收到广播后,取消广播的继续发送,并且可以更改广播的数据.而无序广播是不能取消广播的发送,不可以更改广播的内容.

5. 手机锁屏解锁之广播接收者

  • MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private PhoneScreenListener phoneReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册监听手机解锁/锁屏的广播接收者
phoneReceiver = new PhoneScreenListener();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SCREEN_OFF");
filter.addAction("android.intent.action.SCREEN_ON");
//注册广播接收者
registerReceiver(phoneReceiver, filter);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// 解除注册 的 广播接收者
unregisterReceiver(phoneReceiver);
}
  • PhoneScreenListener.java
1
2
3
4
5
6
7
8
9
10
public class PhoneScreenListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("========= 手机 屏幕 解锁或者锁屏了 ");
}
}

6. 总结

  • 先写一个类继承broadCastReceiver的类

    1
    public class SmsListener extends BroadcastReceiver
  • 写清单配置这个类

    1
    2
    3
    4
    5
    <receiver android:name="com.javami.smslistener.SmsListener">
    <intent-filter android:priority="1000">
    <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
    </intent-filter>
    </receiver>
  • 调节频道接收这个类

    1
    public void onReceive(Context context, Intent intent) {

6.安卓基础之多线程下载&Activity

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. 利用开源框架-xUtils-master-实现多线程下载

  • 需要开启如下权限
1
2
3
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
  • 实现代码
1
2
3
4
5
6
7
8
9
10
11
12
13
public void download(View v){
String path = ed_path.getText().toString().trim();
HttpUtils util = new HttpUtils();
util.download(path, "/mnt/sdcard/jjyy.exe", true, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
toastshow.setText("下载成功");
}
@Override
public void onFailure(HttpException error, String msg) {
toastshow.setText("下载失败!");
}
});

2. 多界面应用的实现

多界面应用的实现

每个应用都可以实现多个界面,如果一个应用需要多个界面,那么需要在应用中添加多个activity就可以.

一般情况下,一个应用内部的组件可以使用显示意图也可以使用隐式意图去激活这个组件,但是如果一个外部应用中,想激活另一个应用的组件时,一般推荐使用隐式意图.

  • 从AndroidManifest.xml注册一个Activity
1
2
3
4
5
6
7
8
<!-- 注册一个activity -->
<activity android:name=".SecondActivity">
<intent-filter>
<!-- MAIN : 表示程序入口,LAUNCHER : 表示应用程序可以从laucher启动 -->
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
  • 设置两个activity_main.xml布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!-- activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.javami.twoactivity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
<!-- activity_main2.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.javami.twoactivity.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World2!" />
</RelativeLayout>
```在SecondActivity引入新的布局文件
```java
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}

2.1 人品计算器的实现

  • 务必注册一个活动
1
<activity android:name=".SecondActivity"></activity>
  • activity_main.xml的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/rgb"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/male"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/female"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="女" />
<RadioButton
android:id="@+id/unknown"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="未知" />
</RadioGroup>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/ed_name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="3" />
<Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="cacl"
android:text="计算" />
</LinearLayout>
<TextView
android:id="@+id/rp_value"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
  • activity_main2.xml的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#44ff0000"
tools:context=".MainActivity" >
<TextView
android:id="@+id/rp_value"
android:text="我是第二个界面"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
  • MainActivity.java的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainActivity extends AppCompatActivity {
private EditText ed_name;
private TextView tv_rp;
private RadioGroup rgb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_name = (EditText)findViewById(R.id.ed_name);
tv_rp = (TextView) findViewById(R.id.rp_value);
rgb = (RadioGroup)findViewById(R.id.rgb);
}
public void cacl(View v){
String name = ed_name.getText().toString().trim();
if(TextUtils.isEmpty(name)){
Toast.makeText(this,"姓名不能为空",0).show();
return;
}
//将内容A--->B
Intent intent = new Intent();
intent.setClass(this,SecondActivity.class);
intent.putExtra("name",name);
intent.putExtra("sex",rgb.getCheckedRadioButtonId());
intent.putExtra("img", BitmapFactory.decodeResource(getResources(),R.drawable.cat));
startActivity(intent);
}
}
  • SecondActivity.java的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class SecondActivity extends Activity {
private TextView rp_value;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
rp_value = (TextView)findViewById(R.id.rp_value);
iv = (ImageView)findViewById(R.id.iv);
//拿到激活SecondActivity是那个意图的对象
Intent intent = getIntent();
String name = intent.getStringExtra("name");
int sex = intent.getIntExtra("sex",R.id.male);
Bitmap img = intent.getParcelableExtra("img");
iv.setImageBitmap(img);
byte[] bb = null;
try{
switch (sex){
case R.id.male:
//将UTF-8编码变为二进制数据
bb = name.getBytes();
break;
case R.id.female:
bb = name.getBytes("gbk");
break;
case R.id.unknown:
bb = name.getBytes("iso8859-1");
break;
default:
break;
}
}catch (Exception e){
e.printStackTrace();
}
byte[] result = bb;
int total = 0;
for (byte b : result){
int data = b&0xff;
total = total+Math.abs(data);
}
int rp = total%100;
String data = null;
if(rp>90){
data = "good!";
}else if (rp>60){
data = "happy";
}else if(rp>30){
data = "sad";
}else{
data = "I'm 5555...";
}
rp_value.setText(data);
}
}

2.2 短信助手的应用

  • 开启短信发送权限与活动的注册
1
2
3
4
<activity android:name=".SmsAcitivityList"></activity>
<activity android:name=".ContactListActivity"></activity>
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
  • activity_main.xml的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/ed_contact"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="请输入联系人" />
<Button
android:onClick="selectContact"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+" />
</LinearLayout>
<EditText
android:id="@+id/sms_body"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入短信内容"
android:lines="5" />
<Button
android:onClick="selectMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选择短信的模版" />
<Button
android:onClick="sendmsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点击发送短信" />
</LinearLayout>
  • contact_item.xml的写法
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</TextView>
  • contactslist.xml的写法
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/contacts_lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
  • smsitem.xml的写法
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</TextView>
  • smslist.xml的写法
1
2
3
4
5
6
7
8
9
10
11
12
<?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" >
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
></ListView>
</LinearLayout>
  • ContactListActivity.java的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Created by 诸葛亮 on 2016/11/20.
*/
public class ContactListActivity extends Activity {
String[] contacts ={
"13987654321",
"18217180124",
"13687987653",
"13687987222",
"13687987555",
"13687987666",
};
private ListView contacts_lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactslist);//需要传入菜单
contacts_lv = (ListView)findViewById(R.id.contacts_lv);
contacts_lv.setAdapter(new ArrayAdapter<String>(this,R.layout.contact_item,contacts));
//添加一个item监听器
contacts_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String contact = contacts[position];
Intent intent = new Intent();
intent.putExtra("contact",contact);
setResult(0,intent);
finish();
}
});
}
}
  • MainActivity.java的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class MainActivity extends AppCompatActivity {
private EditText sms_body;
private EditText ed_contact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sms_body = (EditText)findViewById(R.id.sms_body);
ed_contact = (EditText)findViewById(R.id.ed_contact);
}
//选择联系人
public void selectContact(View v){
Intent intent = new Intent();
intent.setClass(this,ContactListActivity.class);
startActivityForResult(intent,1);
}
//选择短信
public void selectMsg(View v){
Intent intent = new Intent();
intent.setClass(this,SmsAcitivityList.class);
startActivityForResult(intent,2);
}
//发送普通文本内容内的短信,使用的是SmsMessage类的sendTextMessage()方法
//首先调用SmsMessage类的getDefault()方法获取到SmsMessage的实例对象
final SmsManager smsManager = SmsManager.getDefault();
public void sendmsg(View v){
/*
* destinationAddress:手机号码
* scAddress:服务中心号码
* text:短信内容
* sentIntent:PendingIntent,信息发送成功或失败时触发
* deliveryIntent:PendingIntent,信息抵达收件人触发
*/
System.out.print(ed_contact.getText().toString().trim());
smsManager.sendTextMessage(ed_contact.getText().toString().trim(),null,sms_body.getText().toString().trim(),null,null);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==1){
if(data!=null){
String contact = data.getStringExtra("contact");
ed_contact.setText(contact);
}
}else if (requestCode==2){
if(data!=null){
String msg = data.getStringExtra("msg");
sms_body.setText(msg);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
  • SmsAcitivityList.java的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Created by 诸葛亮 on 2016/11/20.
*/
public class SmsAcitivityList extends Activity {
private ListView lv;
String[] msgs = {
"想到你的名字心就会砰砰跳!看到你的容颜脸就会火辣辣烧!牵你的手像云朵轻轻飘!你可知道?我被你彻底迷倒!发誓要和你一起变老",
"你是否愿意给我一个依靠:可以让我在红尘的烦恼与喧嚣中一想到你,就会有甜蜜的平静和无穷的动力,就会有足够的勇气继续向前走。",
"命运让我们相遇,让我沉醉在你的眼眸里。我想陪着你,为你阻挡一生的风雨。请你相信,我会让你的生命,充满快乐回忆!",
"我会把心里最好的地方留给你,只要你敲敲门,我就拥你入怀。因为爱你,愿意为你在这世界造一处平台,与你纵观爱情的古往今来。",
"不经意间,相遇;不经意间,相惜;不经意间,刻骨;不经意间,铭记;不经意间,爱上了你。看似不经意,但我真的很在意。",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smslist);
lv = (ListView)findViewById(R.id.lv);
//设置一个适配器,将意图的内容出传递进去
lv.setAdapter(new ArrayAdapter<String>(this,R.layout.smsitem,msgs));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String msg = msgs[position];
Intent intent = new Intent();
intent.putExtra("msg",msg);
setResult(0,intent);
finish();
}
});
}
}

2.3 给一段文字使用版权链接

  • 开启联网权限
1
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
  • 基础代码的写法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainActivity extends AppCompatActivity {
private TextView links;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
links = (TextView)findViewById(R.id.links);
/*
*
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:scheme="about" />
<data android:scheme="javascript" />
</intent-filter>
*/
links.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://www.fkcat.com"));
startActivity(intent);
}
});
}
}

3. 总结

加强与总结,多实践代码!并且看谷歌官方文档!

5.安卓基础之网络编程&开源框架&多线程下载

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. 简单的xml联网读取

  • 需要在AndroidManifest.xml开启权限
    <uses-permission android:name="android.permission.INTERNET"/>

  • 定义一个工具流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class StreamTool {
public static String decodeStream(InputStream in) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[]buf = new byte[1024];
int len = 0;
while((len=in.read(buf))>0){
baos.write(buf,0,len);
}
return baos.toString();
}
}
  • 定义一个NewsItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class NewsItem {
private String title;
private String description;
private String image;
private String type;
private String comment;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
  • 定义一个NewsService,通过处理数据返回List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class NewsService {
public static List<NewsItem> getAllNewsItem(final String path){
final List<NewsItem> items = new ArrayList<NewsItem>();
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时时间
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, "utf-8");
int type = parser.getEventType();
NewsItem item=null;
while(type!=XmlPullParser.END_DOCUMENT){
if(type==XmlPullParser.START_TAG){
if("item".equals(parser.getName())){
item = new NewsItem();
}else if("title".equals(parser.getName())){
item.setTitle(parser.nextText());
}else if("description".equals(parser.getName())){
item.setDescription(parser.nextText());
}else if("image".equals(parser.getName())){
item.setImage(parser.nextText());
}else if("type".equals(parser.getName())){
item.setType(parser.nextText());
}else if("comment".equals(parser.getName())){
item.setComment(parser.nextText());
}
}else if(type==XmlPullParser.END_TAG){
//将 item 添加到一个 list集合中
if(item!=null){
items.add(item);
}
}
type = parser.next();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
return items;
}
}
  • 定义一个MainActivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
public class MainActivity extends AppCompatActivity {
private String path = "http://www.itceo.net/test/news.xml";
private List<NewsItem> items =null;
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
items = NewsService.getAllNewsItem(path);
// 将item中的数据绑定到屏幕显示
loadData();
}
//声明adapter
private MyAdapter myadapter;
private void loadData() {
if(myadapter==null){
myadapter = new MyAdapter();
lv.setAdapter(myadapter);
}else{
//通知数据改变
myadapter.notifyDataSetChanged();
}
}
private class MyAdapter extends BaseAdapter{
//指定到底有多少个item要显示在 lv 中
@Override
public int getCount() {
return items.size();
}
//这个方法是在每次显示一个item时会被调用到的
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v ;
if(convertView==null){
v=View.inflate(MainActivity.this, R.layout.item, null);
}else{
v = convertView;
}
//拿到当前位置newsItem对象
NewsItem newsItem = items.get(position);
//找到item中每个 控件
SmartImageView siv = (SmartImageView) v.findViewById(R.id.item_iv);
TextView title= (TextView) v.findViewById(R.id.item_title);
TextView desc = (TextView) v.findViewById(R.id.item_desc);
TextView type = (TextView) v.findViewById(R.id.item_type);
title.setText(newsItem.getTitle());
desc.setText(newsItem.getDescription());
String tp = newsItem.getType();
if("1".equals(tp)){
//就是评论
type.setText("评论: "+ newsItem.getComment());
type.setTextColor(Color.YELLOW);
}else if("2".equals(tp)){
//就是视频
type.setText("视频");
type.setTextColor(Color.RED);
}else if("3".equals(tp)){
// 就是直播
type.setText("Live直播 ");
type.setTextColor(Color.BLUE);
}
//利用开源图片显示库
siv.setImageUrl(newsItem.getImage());
return v;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
}
  • activity_main.xml与item.xml的编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
></ListView>
</LinearLayout>
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.loopj.android.image.SmartImageView
android:id="@+id/item_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/item_title"
android:text="标题"
android:layout_toRightOf="@id/item_iv"
android:layout_width="fill_parent"
android:textSize="20sp"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/item_desc"
android:textSize="15sp"
android:layout_below="@id/item_title"
android:lines="2"
android:text="描述xxxxxxxxxxxxxxxx"
android:textColor="#55000000"
android:layout_toRightOf="@id/item_iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/item_type"
android:layout_below="@id/item_desc"
android:textSize="15sp"
android:text="类型:"
android:textColor="#55000000"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<View
android:background="#44ffffff"
android:layout_width="fill_parent"
android:layout_height="1dip"
/>
</RelativeLayout>

2. get与post的关系

get与post的关系

2.1 get的关系

如果在发送数据的过程中,传输了中文数据,那么是需要进行url编码的,否则带不过去.

1
2
3
4
http://192.168.1.100:8080/web_login/login?number=%E5%93%88%E5%93%88&pwd=520
http://192.168.1.100:8080/web_login/login?number=5201314&pwd=520
path = path+"number="+URLEncoder.encode(number, "UTF-8")+"&pwd="+URLEncoder.encode(pwd, "UTF-8");

2.2 post的关系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
// Content-Type: application/x-www-form-urlencoded
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//准备好数据 ---- number=erwan&pwd=456
String data = "number="+URLEncoder.encode(number, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");
//Content-Length: 20
conn.setRequestProperty("Content-Length", data.length()+"");
//这个地方表示告诉加了一个标志, 要给服务器写数据了
conn.setDoOutput(true);
conn.getOutputStream().write(data.getBytes());

2.3 apache-httpclient-get

1
2
3
4
5
6
7
8
9
10
11
12
13
//客户端浏览器
HttpClient client = new DefaultHttpClient();
//get 方式请求的必要的参数
HttpGet get = new HttpGet(path);
//http://192.168.1.100:8080/web_login/login
//收到的来自于服务器端的响应的 数据
HttpResponse response = client.execute(get);
// HTTP/1.1 200 OK
int code = response.getStatusLine().getStatusCode();

2.4 apache-httpclient-post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//客户端浏览器
HttpClient client = new DefaultHttpClient();
//指定了发送的请求的方式
HttpPost post = new HttpPost(path);
//传递给服务器要带过去的参数的信息
List<NameValuePair> list = new ArrayList<NameValuePair>();
//将带过去的参数放到一个nameValuePair 中, 然后再放到 一个list 中,然后再将这个list给要带过去的数据实体
list.add(new BasicNameValuePair("number", number));
list.add(new BasicNameValuePair("pwd", pwd));
//设置带给服务器的参数的信息
//number=5201314&pwd=123
//设置要带给服务器的数据实体
post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
//http://192.168.1.100:8080/web_login/login
//收到的来自于服务器端的响应的数据
HttpResponse response = client.execute(post);
//http 的相应分为响应行,响应头,响应体
//HTTP/1.1 200 OK
int code = response.getStatusLine().getStatusCode();

2.5 开源android-async-http-master-get

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
String path = "http://192.168.1.100:8080/web_login/login?number="+number+"&pwd="+pwd;
AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() {
//请求成功的时候 会被调用的
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
tv_status.setText(new String(responseBody));
}
//请求失败的时候会被调用的
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
error.printStackTrace(System.out);
Toast.makeText(MainActivity.this, "对不起, 俺错误了...", 0).show();
}
});

2.6 开源android-async-http-master-post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
String path = "http://192.168.1.100:8080/web_login/login";
AsyncHttpClient client = new AsyncHttpClient();
//封装了api , 使用到了handler 去 处理了 这些事儿 ...
RequestParams params = new RequestParams();
// number=5201314&pwd=123
params.add("number", number);
params.add("pwd", pwd);
client.post(path, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
tv_status.setText(new String(responseBody));
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
error.printStackTrace(System.out);
Toast.makeText(MainActivity.this, "出错误了 ", 0).show();
}
});

3. 多线程与断点续传实现

多线程推导

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
public class ThreadDownload {
//规定下载服务端的资源使用3条线程去下载
private static int threadCount = 3;
private static int currentRunningThread = 3;
private static String path = "http://down.qq.com/cf/dltools/CrossFire_OBV4.0.5.0_Full_QQVIPDL_speeded_signed.exe";
public static void main(String[] args) {
try{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if(code==200){
//拿到文件的长度大小
int length = conn.getContentLength();
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(length);
raf.close();
//启动线程去下载文件
//获得每块线程的平均大小
int blockSize = length / threadCount; //总文件长度大小/3
//threadId:线程的id threadcount:几条线程下载
for(int threadId=0;threadId<threadCount;threadId++){
int startIndex = threadId * blockSize; //0~2
int endIndex = (threadId+1)*blockSize-1;//3~5
//如果线程是最后的一个线程
if(threadId==(threadCount-1)){
endIndex = length-1;
}
new DownloadFilePartThread(threadId,startIndex,endIndex).start();
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static class DownloadFilePartThread extends Thread{
//线程的id号
private int threadId;
//线程的下载开始位置
private int startIndex;
//线程的下载的结束位置
private int endIndex;
//当前线程下载到的位置
private int currentPostion;
public DownloadFilePartThread(int threadId,int startIndex,int endIndex){
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
currentPostion = startIndex;
}
public void run(){
System.out.println("第 " + threadId + "线程开始 下载了 : 下载 从 "
+ startIndex + "~ " + endIndex);
try{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
// 在多线程下载的时候,每条线程只需要目标文件的一部分的数据
// 需要告诉服务器,只需要那一段的数据
// 通过设置 http的请求头可以去实现 ,告诉 服务器,只需要目标 段的数据
// startIndex ---- endIndex
conn.setRequestProperty("range", "bytes="+startIndex+"-"+endIndex);
//获得服务器返回的目标段的数据
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
File ilf = new File(threadId+".position");
if(ilf.exists()&&ilf.length()>0){
BufferedReader br = new BufferedReader(new FileReader(ilf));
String vl = br.readLine();
int alreadyWritePosition = Integer.parseInt(vl);
//告诉服务器要数据的时候 ,从这个位置开始要
conn.setRequestProperty("range", "bytes="+alreadyWritePosition+"-"+endIndex);
raf.seek(alreadyWritePosition);
System.out.println("下载过了!");
}else{
System.out.println("没下载过!");
conn.setRequestProperty("range", "bytes="+startIndex+"-"+endIndex);
//表示从哪里开始
raf.seek(startIndex);
}
int code = conn.getResponseCode();
if(code == 206){
//拿到数据
InputStream in = conn.getInputStream();
int len = 0;
byte[]buf = new byte[1024*1024*1024*1024*1024*1024*1024*1024*1024];
while((len=in.read(buf))>0){
raf.write(buf,0,len);
//将实时的位置记录了之后,方便下面紧接着去往文件中去写
currentPostion = currentPostion + len;
File info = new File(threadId+".position");
RandomAccessFile rf = new RandomAccessFile(info, "rwd");
rf.write(String.valueOf(currentPostion).getBytes());
rf.close();
}
in.close();
raf.close();
}
System.out.println("第 " + threadId + "线程下载 结束了");
// 等着所有的线程都下载完成再删文件
// 弄一个 计数器,记住总共有多少条线程正在下载,每当一条线程下载完成,走到这里的时候,就将计数器-1 一下
// 当发现计数器小于或者等于0 的时候,说明没有线程正在下载,所以这个时候,再去删记录了下载位置的文件
synchronized (ThreadDownload.class) {
currentRunningThread--;
if(currentRunningThread<=0){
//将记录下载位置的文件删除
for(threadId=0;threadId<threadCount;threadId++){
File fff = new File(threadId+".position");
fff.renameTo(new File(threadId+".position.finish"));
File fll = new File(threadId+".position.finish");
fll.delete();
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
private static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index+1);
}
}

4. 总结

多线程下载还需要深入了解.

4.安卓基础之网络编程&json解析

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. ListView的使用步骤

  • 首先在layout文件中定义一个listview
  • 找到定义的listview控件,设置一个适配器(adapter)
  • 在适配器中将要绑定listview中的数据传递给adapter

MVC 的设计思想

  • M:数据
  • V:listview
  • C:adapter

2. AnimationDrawable 的使用:

  • 先在drawable准备好图片
  • 在xml文件里面设置根元素和子原始
  • 代码中调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
AnimationDrawable rocketAnimation;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rocketAnimation.start();
return true;
}
return super.onTouchEvent(event);
}

3. Android的国际化相关

常见的有:
zh_cn: 简体中文
zh_hk: 繁体中文(中国香港)
zh_tw: 繁体中文(中国台湾地区)
en-hk: 英语(香港)
en_us: 英语(美国)
en_gb: 英语(英国)
en_ww: 英语(全球)
ja_jp: 日语(日本)
ko_kr: 韩文(韩国)

在Android工程的res目录下,通过定义特殊的文件夹名称就可以实现多语言支持.比如我们的程序兼容简体中文/英文,在values文件夹中建立默认strings.xml,再建立values-zh-rCN文件夹.

在每个文件夹里放置一个strings.xml,strings.xml里是各种语言字符串.如果涉及到参数配置类xml文件夹名称也要改成xml-zh/xml.这样在android的系统中进行语言切换,所开发的程序也会跟着切换语言.

1
2
3
4
5
Resources resources = getResources();//获得res资源对象
Configuration config = resources.getConfiguration();//获得设置对象
DisplayMetrics dm = resources .getDisplayMetrics();//获得屏幕参数:主要是分辨率,像素等.
config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文
resources.updateConfiguration(config, dm);

4. Android 连接网络,获得数据

  • 先定义一个秘书:Handler handler = new Handler()
  • 获取到一个篮子:Message msg = Message.obtain();
  • 让篮子交给秘书处理:msg.obj = data;
    通过生活的例子融入代码的想法中,在耗时的事儿不允许放在主线程中去完成.

4.1 在线获得网址的图片

  • 需要在AndroidManifest.xml开启权限
1
<uses-permission android:name="android.permission.INTERNET"/>
  • 在主线程重写handler的handleMessage( )方法,在工作线程发送消息.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
public class MainActivity extends AppCompatActivity {
protected static final int SUCCESS = 0;
protected static final int NETWORK_ERROR = 1;
protected static final int ERROR = 2;
private EditText ed_path;
private ImageView iv;
private String path;
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
//取出消息中的数据
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
break;
case NETWORK_ERROR:
Toast.makeText(MainActivity.this, "连接错误 ....", 0).show();
break;
case ERROR:
Toast.makeText(MainActivity.this, " 获得资源失败 ....", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_path = (EditText) findViewById(R.id.ed_path);
iv = (ImageView) findViewById(R.id.iv);
}
public void gogetImage(View v){
path = ed_path.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(this, "路径有错误...", 0).show();
return;
}
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
//设置请求的方式
conn.setRequestMethod("GET");
//拿到返回的数据的类型
String contentType = conn.getContentType();
//数据的长度
int length = conn.getContentLength();
// 获得服务器返回的状态码 , 根据状态码去判断是否成功
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Message msg = Message.obtain();
msg.what=SUCCESS;
msg.obj = bitmap;
mHandler.sendMessage(msg);
in.close();
}else{
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
Message message = Message.obtain();
message.what= NETWORK_ERROR;
mHandler.sendMessage(message);
e.printStackTrace();
}
};
}.start();
}
}
  • activity_main.xml的实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".MainActivity"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/ed_path"/>
<Button
android:onClick="gogetImage"
android:text="Get"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

4.2 网页源码查看器的实现

  • 需要在AndroidManifest.xml开启权限
1
<uses-permission android:name="android.permission.INTERNET"/>
  • 在主线程中重写hander的handleMessage()方法,让工作线程发送信息.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class MainActivity extends AppCompatActivity {
protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
protected static final int NETWORK_ERROR = 2;
private EditText ed_path;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_path = (EditText) findViewById(R.id.ed_path);
tv = (TextView)findViewById(R.id.tv);
}
//定义一个秘书
Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case SUCCESS:
String value = (String) msg.obj;
tv.setText(value);
break;
case ERROR:
Toast.makeText(MainActivity.this,"ERROR",0).show();
break;
case NETWORK_ERROR:
Toast.makeText(MainActivity.this,"NETWORK_ERROR",0).show();
break;
default:
break;
}
}
};
String path = null;
public void viewPageSource(View view){
path = ed_path.getText().toString().trim();
if(TextUtils.isEmpty(path)){
Toast.makeText(MainActivity.this,"PATH NOT NOT!",0).show();
return;
}
//否则连接网络,启动一个新的线程
new Thread(){
public void run(){
try{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置连接超时为5秒钟
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//这句能伪装成电脑访问
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
String contentType = conn.getContentType();
int code = conn.getResponseCode();
if(code == 200){
InputStream in = conn.getInputStream();
String data = StreamTool.decodeStream(in);
//Message 称为篮子
Message msg = Message.obtain();
msg.what = SUCCESS;
msg.obj = data;
handler.sendMessage(msg);
}else{
Message msg = Message.obtain();
msg.what = ERROR;
handler.sendMessage(msg);
}
}catch (Exception e){
Message msg = Message.obtain();
msg.what = NETWORK_ERROR;
handler.sendMessage(msg);
}
}
}.start();
}
  • 定义一个底层流实现代码
1
2
3
4
5
6
7
8
9
10
11
public static String decodeStream(InputStream in) throws IOException{
//底层流
ByteArrayOutputStream bas = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len=in.read(buf))>0){
bas.write(buf,0,len);
}
String data = bas.toString();
return data;
  • activity_mail.xml的编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/ed_path"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://www.itceo.net"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="viewPageSource"
android:text="显示"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>

4.3 解析json格式的数据

  • 需要在AndroidManifest.xml开启权限
1
<uses-permission android:name="android.permission.INTERNET"/>
  • 在主线程中重写hander的handleMessage()方法,让工作线程发送信息.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class MainActivity extends AppCompatActivity {
private EditText ed_city;
private TextView city_result1;
private TextView city_result2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_city = (EditText) findViewById(R.id.ed_city);
city_result1 = (TextView) findViewById(R.id.city_result1);
city_result2 = (TextView) findViewById(R.id.city_result2);
}
private final static String PATH = "http://wthrcdn.etouch.cn/weather_mini?city=";
protected static final int SUCCESS = 0;
protected static final int INVALID_CITY = 1;
protected static final int ERROR = 2;
private String city;
String ul;
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS:
try {
JSONArray data = (JSONArray) msg.obj;
String day01 = data.getString(0);
city_result1.setText(day01);
String day02 = data.getString(1);
city_result2.setText(day02);
} catch (Exception e) {
e.printStackTrace();
}
break;
case INVALID_CITY:
Toast.makeText(MainActivity.this, "城市无效", 0).show();
break;
case ERROR:
Toast.makeText(MainActivity.this, "网络问题", 0).show();
break;
default:
break;
}
};
};
public void searchCityWeather(View v){
city = ed_city.getText().toString().trim();
if(TextUtils.isEmpty(city)){
Toast.makeText(this, "路径错误...", 0).show();
return;
}
//http://wthrcdn.etouch.cn/weather_mini?city=%E6%B7%B1%E5%9C%B3
new Thread(){
public void run() {
try {
ul = PATH + URLEncoder.encode(city, "UTF-8");
URL url = new URL(ul);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置必要的参数信息
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//判断响应码
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
String data = StreamTool.decodeStream(in);
System.out.println(data);
//解析json格式的数据
JSONObject jsonObj = new JSONObject(data);
// 获得desc的值
String result = jsonObj.getString("desc");
if("OK".equals(result)){
//城市有效,返回了需要的数据
JSONObject dataObj = jsonObj.getJSONObject("data");
JSONArray jsonArray = dataObj.getJSONArray("forecast");
//通知更新ui
Message msg = Message.obtain();
msg.obj = jsonArray;
msg.what=SUCCESS;
mHandler.sendMessage(msg);
}else{
//城市无效
Message msg = Message.obtain();
msg.what=INVALID_CITY;
mHandler.sendMessage(msg);
}
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
}
};
}.start();
}
}
  • 定义一个底层流实现代码
1
2
3
4
5
6
7
8
9
10
public static String decodeStream(InputStream in) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len=in.read(buf))>0){
baos.write(buf,0,len);
}
String data = buf.toString();
return data;
}
  • activity_mail.xml的编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请输入要查询的城市"/>
<EditText
android:id="@+id/ed_city"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="searchCityWeather"
android:text="查询"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/city_result1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/city_result2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

4.4 联网解析xml格式的数据

  • 需要在AndroidManifest.xml开启权限
1
<uses-permission android:name="android.permission.INTERNET"/>
  • 在主线程重写handler的handleMessage( )方法,在工作线程发送消息.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
public class MainActivity extends AppCompatActivity {
protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
private EditText ed_phone;
private TextView tv_phonenumber;
private TextView tv_phonelocation;
private TextView tv_phonejx;
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
dialog.dismiss();
switch (msg.what) {
case SUCCESS:
p = (Product) msg.obj;
if(p!=null){
tv_phonenumber.setText(p.getPhonenum());
tv_phonelocation.setText(p.getLocation());
tv_phonejx.setText(p.getPhoneJx());
}
break;
case ERROR:
Toast.makeText(MainActivity.this, "对不起, 俺比较忙, 稍后再来 ", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_phone = (EditText) findViewById(R.id.ed_phone);
tv_phonenumber = (TextView) findViewById(R.id.tv_phonenumber);
tv_phonelocation = (TextView) findViewById(R.id.tv_phonelocation);
tv_phonejx = (TextView) findViewById(R.id.tv_phonejx);
}
String number;
Product p = null;
ProgressDialog dialog = null;
public void getPhoneJX(View v){
number = ed_phone.getText().toString().trim();
if(TextUtils.isEmpty(number)){
Toast.makeText(this, "手机号码 错误 ", 0).show();
return;
}
// http://www.096.me/api.php?phone=13691689110&mode=xml
final String path ="http://www.096.me/api.php?phone="+number+"&mode=xml";
dialog = new ProgressDialog(this);
dialog.setMessage("正在玩命加载中...");
dialog.show();
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
String data = StreamTool.decodeStream(in);
XmlPullParser parser = Xml.newPullParser();
if(data.contains("gbk")){
parser.setInput(in, "gbk");
}else if(data.contains("UTF-8")){
parser.setInput(in, "UTF-8");
}
//以后注意, 只要出现乱码, 确保 解析的 编码和 发过来的编码一致 , 就不会有什么问题了.
//获得事件的类型
int eventType = parser.getEventType();
//
while(eventType!=XmlPullParser.END_DOCUMENT){
// .. //准备 一个javabean ,封装数据到 bean 中 -- Product
/*
<smartresult>
<product type="mobile">
<phonenum>13691689110</phonenum>
<location>广东深圳移动神州行卡</location>
<phoneJx>惨淡经营,难免贫困,此数不吉,最好改名 凶</phoneJx>
</product>
</smartresult>
*/
if(eventType==XmlPullParser.START_TAG){
if("product".equals(parser.getName())){
// new 一个product ,准备封装数据
String type = parser.getAttributeValue(0);
p = new Product();
p.setType(type);
}else if("phonenum".equals(parser.getName())){
p.setPhonenum(parser.nextText());
}else if("location".equals(parser.getName())){
p.setLocation(parser.nextText());
}else if("phoneJx".equals(parser.getName())){
p.setPhoneJx(parser.nextText());
}
}
eventType =parser.next();
}
//发消息 , 通知秘书去更新UI
Message msg = Message.obtain();
msg.what=SUCCESS;
msg.obj = p;
mHandler.sendMessage(msg);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
}
};
}.start();
}
}
  • 定义一个底层流实现代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.javami.unitls;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by 诸葛亮 on 2016/10/30.
*/
public class StreamTool {
public static String decodeStream(InputStream in) throws IOException{
//底层流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))>0){
baos.write(buf,0,len);
}
String data = baos.toString();
if (data.contains("gbk")){
return baos.toString("gbk");
}else if(data.contains("utf-8")){
return baos.toString("utf-8");
}else{
return data;
}
}
}
  • 定义Product封装数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.javami.unitls;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by 诸葛亮 on 2016/10/30.
*/
public class StreamTool {
public static String decodeStream(InputStream in) throws IOException{
//底层流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len=in.read(buf))>0){
baos.write(buf,0,len);
}
String data = baos.toString();
if (data.contains("gbk")){
return baos.toString("gbk");
}else if(data.contains("utf-8")){
return baos.toString("utf-8");
}else{
return data;
}
}
}
  • activity_mail.xml的编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请输入手机号码" />
<EditText
android:inputType="phone"
android:id="@+id/ed_phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:onClick="getPhoneJX"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_phonenumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv_phonelocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv_phonejx"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

3.安卓基础之数据库&listview&对话框

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. Android的xml的解析器

1.1 XML解析案例

  • 解析手机号码吉凶案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//使用xml pull 解析器去解析xml文件的内容
XmlPullParser parser = Xml.newPullParser();
try {
InputStream in = getAssets().open("result.xml");
parser.setInput(in, "gbk");
//获取事件的类型
int eventType = parser.getEventType();
/*
<?xml version="1.0" encoding="gbk"?>
<smartresult>
<product type="mobile">
<phonenum>13512345678</phonenum>
<location>重庆移动神州行卡</location>
<phoneJx>有得有失,华而不实,须防劫财,始保平安 吉带凶</phoneJx>
</product>
</smartresult>
*
*/
Product p = null;
while(eventType!=XmlPullParser.END_DOCUMENT){
//判断是否是元素的开始,只要是某个元素的开始位置,那么就会进入
//获得当前元素解析的元素的名称
if("product".equals(parser.getName())){
p = new Product();
String type = parser.getAttributeValue(0);//product
p.setType(type);
}else if("phonenum".equals(parser.getName())){
String phonenum = parser.nextText();
p.setPhonenum(phonenum);
}else if("location".equals(parser.getName())){
String location = parser.nextText();
p.setLocation(location);
}else if("phoneJx".equals(parser.getName())){
String phoneJx = parser.nextText();
p.setPhoneJx(phoneJx);
}
//手动挪动指针
eventType = parser.next();
}
if(p!=null){
Log.d("ProductMessange",p.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
1
2
3
4
5
6
7
8
9
10
11
result.xml
<?xml version="1.0" encoding="gbk"?>
<smartresult>
<product type="mobile">
<phonenum>13512345678</phonenum>
<location>重庆移动神州行卡</location>
<phoneJx>有得有失,华而不实,须防劫财,始保平安 吉带凶
</phoneJx>
</product>
</smartresult>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Product.java
package com.example.xmlpullparsertest;
/*
*
* 封装数据的 标 准的 javabean
*
<product type="mobile">
<phonenum>13512345678</phonenum>
<location>重庆移动神州行卡</location>
<phoneJx>有得有失,华而不实,须防劫财,始保平安 吉带凶</phoneJx>
</product>
*
*/
public class Product {
private String type;
private String phonenum;
private String phoneJx;
private String location;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getPhoneJx() {
return phoneJx;
}
public void setPhoneJx(String phoneJx) {
this.phoneJx = phoneJx;
}
@Override
public String toString() {
return "Product [type=" + type + ", phonenum=" + phonenum
+ ", phoneJx=" + phoneJx + "]";
}
}

2. 保存数据到数据库中的作用

如果保存的数据是有规律的,格式是同样的.那么可以去选择使用数据库保存数据.Android提供的数据库(sqlite)数据库.

  • android提供的数据库小应用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySqliteHelper helper = new MySqliteHelper(MainActivity.this);
helper.getReadableDatabase();
}
MySqliteHelper.java
package com.example.sqlitedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySqliteHelper extends SQLiteOpenHelper {
public MySqliteHelper(Context context){
//context:应用上下文
//name:数据库的名词
//factory:创建游标的工厂
//version:数据库的版本
super(context, "mydb1", null, 4);
/*
mysql
create table users(
id int primary key auto_increment,
name varchar(30)
);
android 中 :
create table students(
id integer primary key autoincrement,
name varchar(30)
);
*/
}
//在数据库首次被创建时调用
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table students ( _id integer primary key autoincrement,name varchar(30), sex varchar(10))");
}
//在数据库升级时调用,当版本比之前的版本高时会执行该方法!
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table students add number varchar(10)");
}
}
  • StudentSystem在SQLiteOpenHelper的应用详细版
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
Student.java
package domain;
public class Student {
private String id;
private String name;
private String sex;
public Student(){
}
public Student(String id,String name,String sex){
this.name = name;
this.id = id;
this.sex = sex;
}
public String getId() {
return id;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
StudentDao.java
package com.example.studentsystemdemo1;
import java.util.ArrayList;
import java.util.List;
import domain.Student;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class StudentDao {
StudentDbOpenHelper helper;
public StudentDao(Context context){
helper = new StudentDbOpenHelper(context);
}
public void add(Student st){
//拿到工具类的实例,然后去操作数据库
SQLiteDatabase db = helper.getReadableDatabase();
//执行sql语句
db.execSQL("insert into students values(null,?,?)",new Object[]{st.getName(),st.getSex()});
}
public void delete(String id){
SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("delete from students where _id=?",new Object[]{id});
}
public void update(Student st){
SQLiteDatabase db = helper.getReadableDatabase();
db.execSQL("update students set name=?,sex=? where _id=?", new Object[]{st.getName(),st.getSex(),st.getId()});
}
public Student find(String id){
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from students where _id=?", new String[]{id});
boolean result = cursor.moveToNext();
Student st = null;
if(result){
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
st = new Student(String.valueOf(id),name,sex);
}
cursor.close();
return st;
}
//查询返回所有学生的信息
public List<Student> getAll(){
List<Student> list = new ArrayList<Student>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from students", null);
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
Student st = new Student(String.valueOf(id),name,sex);
list.add(st);
}
list = null;
return list;
}
}
StudentDbOpenHelper.java
package com.example.studentsystemdemo1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentDbOpenHelper extends SQLiteOpenHelper {
public StudentDbOpenHelper(Context context){
super(context, "student.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库
db.execSQL("create table students (_id integer primary key autoincrement, name varchar(30),sex varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
  • 学生查询系统带item的应用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/ed_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入学生的姓名" />
<RadioGroup
android:id="@+id/rgb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/male"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/female"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="女" />
</RadioGroup>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="save"
android:text="保存" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
ed_name = (EditText) findViewById(R.id.ed_name);
rgb= (RadioGroup) findViewById(R.id.rgb);
lv = (ListView) findViewById(R.id.lv);
sdao = new StudentDao(this);
refreshView();
}
public void save(View v){
String name = ed_name.getText().toString().trim();
if(TextUtils.isEmpty(name)){
Toast.makeText(this, "学生信息不能为空", 0).show();
return;
}
String sex ="male";
int id = rgb.getCheckedRadioButtonId();
if(id==R.id.male){
sex ="male";
}else{
sex ="female";
}
//将数据 保存到数据库 中去
// 拿到 dao
Student st = new Student("xjlkj",name,sex);
sdao.add(st);
Toast.makeText(this, "保存 "+ name+"成功", 0).show();
//将所有的数据同步的显示 到 屏幕上去
//查询现有的数据
refreshView();
}
List<Student> students;
private MyAdapter myAdapter;
private void refreshView() {
// 将现有的全部给清空一下
students = sdao.getAll();
if(myAdapter ==null){
myAdapter = new MyAdapter();
//为 lv 设置数据适配器 --- 设置控制器controller
lv.setAdapter(myAdapter);
}else{
//则说明myAdapter已经存在了,需要做的是,通知控制器 adapter去更新一下数据.
myAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends BaseAdapter{
//最开始被调用的 , 用于告诉控制器 adapter到底要显示 多少个item
@Override
public int getCount() {
//告诉控制器 adapter显示多少个item
return students.size();
}
//每个item要显示在屏幕上时,又会调用到这个方法
//convertView:就是用来进行优化的
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//获得当前的学生
final Student st = students.get(position);
//现在 item 已经定义好了,需要将硬盘上item.xml布局文件 转化为一个布局的对象返回去.
View v;
if (convertView == null) {
v = View.inflate(MainActivity.this, R.layout.item, null);
} else {
v = convertView;
}
//打气筒的对象 ,去填充xml,使得xml布局文件变为一个view对象.
//拿到iv和tv
ImageView iv = (ImageView) v.findViewById(R.id.item_iv);
String sex = st.getSex();
if("male".equals(sex)){
iv.setImageResource(R.drawable.nan);
}else{
iv.setImageResource(R.drawable.nv);
}
TextView tv = (TextView) v.findViewById(R.id.item_tv);
tv.setText(st.getName());
v.findViewById(R.id.item_delete).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
/*System.out.println("======= onClick 点击了 ");
//需要拿到当前的点击的item ,将 学生的信息给删掉.
//获得点击点击的item
String id = st.getId();
sdao.delete(id);
Toast.makeText(MainActivity.this, "删除成功 : " + st.getName(), 0).show();
//重新加载下数据
refreshView();*/
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("删除...");
builder.setMessage("亲,你确定要删除吗? 不能反悔 的哦...");
//设置点击确定的按钮
builder.setPositiveButton("删除",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String id = st.getId();
sdao.delete(id);
Toast.makeText(MainActivity.this, "删除 成功 : " + st.getName(), 0).show();
// 重新 加载 下 数据
refreshView();
}
});
//设置点击取消的的按钮
builder.setNegativeButton("取消", null);
//你需要 调用 相应的方法 才能够显示出来
/* AlertDialog dialog = builder.create();
dialog.show();*/
builder.show();
}
});
return v;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
}
StudentDao.java
package com.example.studentsystemdemo2;
import java.util.ArrayList;
import java.util.List;
import domain.Student;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class StudentDao {
StudentDbOpenHelper helper;
public StudentDao(Context context){
helper = new StudentDbOpenHelper(context);
}
// "create table students (_id integer primary key autoincrement, name varchar(30),sex varchar(10))"
public void add(Student st){
//拿到工具类的实例, 然后去操作 数据库
SQLiteDatabase db = helper.getWritableDatabase();
//执行sql语句
db.execSQL("insert into students values(null,?,?)",new Object[]{st.getName(),st.getSex()});
}
public void delete(String id){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from students where _id=?",new Object[]{id});
}
public void update(Student st){
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update students set name=?,sex=? where _id=?", new Object[]{st.getName(),st.getSex(),st.getId()});
}
public Student find(String id){
SQLiteDatabase db = helper.getReadableDatabase();
//select * from users where id=?
//叫做游标,与 javaweb中所学的resultSet结构是一样的
Cursor cursor = db.rawQuery("select * from students where _id=?", new String[]{id});
boolean result = cursor.moveToNext();
Student st = null;
if(result){
// st = new Student();
/*int _id = cursor.getInt(0);
String name = cursor.getString(1);
String sex = cursor.getString(2);
st.setId(id);
st.setName(name);
st.setSex(sex);*/
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
st = new Student(String.valueOf(_id),name,sex);
}
// 最后会释放 资源
cursor.close();
return st;
}
//查询返回所有的学生的信息
public List<Student> getAll() {
List<Student> list =new ArrayList<Student>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from students", null);
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
Student st = new Student(String.valueOf(id), name, sex);
list.add(st);
}
return list;
}
}
StudentDbOpenHelper.java
package com.example.studentsystemdemo2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentDbOpenHelper extends SQLiteOpenHelper {
public StudentDbOpenHelper(Context context) {
super(context, "student.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库
db.execSQL("create table students (_id integer primary key autoincrement, name varchar(30),sex varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Student.java
package domain;
public class Student {
private String id;
private String name;
private String sex;
public Student() {
super();
}
public Student(String id, String name, String sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/ed_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入学生的姓名" />
<RadioGroup
android:id="@+id/rgb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/male"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/female"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="女" />
</RadioGroup>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="save"
android:text="保存" />
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
item.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="horizontal" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_marginLeft="15dip"
android:layout_alignParentLeft="true"
android:id="@+id/item_iv"
android:layout_width="20dip"
android:layout_height="30dip"
android:layout_centerVertical="true"
/>
<TextView
android:layout_toRightOf="@id/item_iv"
android:id="@+id/item_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
/>
<ImageView
android:layout_marginRight="8dip"
android:id="@+id/item_delete"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:src="@drawable/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
</LinearLayout>
  • 常见的对话框
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
activity_main.xml
<Button
android:onClick="dialog01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="创建确认取消对话框"/>
<Button
android:onClick="dialog02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="创建单选对话框"/>
<Button
android:onClick="dialog03"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="创建多选对话框"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
MainActivity.java
//创建确认取消对话框
public void dialog01(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("约会吗?");
builder.setMessage("告别单身,你愿意吗?");
//愿意情况下开启监听器
builder.setPositiveButton("愿意", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "我也单身,说不定可以来找我", 0).show();
}
});
builder.setNegativeButton("不愿意", null);
builder.show();
}
//创建单选进度条
public void dialog02(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("单选对话框");
final String[] items = {"小樱","小明","诸葛亮"};
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "被点击了:"+items[which]+",位置:"+which, 0).show();
}
});
builder.show();
}
//创建多选对话框
public void dialog03(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("多选框");
final String[] items ={"android","python","go","c/c++"};
boolean[] checkItems = {true,false,false,true};
builder.setMultiChoiceItems(items, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(MainActivity.this, " 被点击了 : " + items[which] +",位置: " +which+", 值是: "+ isChecked, 0 ).show();
}
});
builder.show();
}
  • 用ContentValues来实现增删改查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
Student.java
package domain;
public class Student {
private String id;
private String name;
private String sex;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String id, String name, String sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}
StudentDao.java
package com.example.studentsystemdemo3;
import domain.Student;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/*
*
* 增删改查有两套api了
*
* 第一套(你经常使用的):
* 增删改:db.execSQL();
* 查询:db.rawQuery();
*
* 第二套(推荐使用):
*
* 增:db.insert();
* 删:db.delete();
* 改:db.update();
* 查询:db.query();
*
* 实际开发过程中:数据库到底用的多不多?不多 ...
*
* 提供的保存数据的方式很多 :
*
* 保存数据的方式 :
* 1. 应用内部的私有的文件夹下 : /data/data/net.itceo.hello/files/cache
* 2. sharedPreference : /data/data/net.itceo.hello/shar_prefs
* 3. 在 sd 卡公共的部分 : /mnt/sdcard
* 4. 存到数据库 中 : sqlite 数据库
*
*
*
*
*/
public class StudentDao {
StudentDbOpenHelper helper;
public StudentDao(Context context){
helper = new StudentDbOpenHelper(context);
}
public void add(Student st){
//拿到 工具类的实例 , 然后去操作 数据库
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", st.getName());
values.put("sex", st.getSex());
db.insert("students", null, values);
}
public void delete(String id){
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("students", "_id=?", new String[]{id});
}
public void update(Student st){
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", st.getName());
values.put("sex", st.getSex());
db.update("students", values, "_id=?", new String[]{st.getId()});
}
public Student find(String id){
SQLiteDatabase db = helper.getReadableDatabase();
db.query("students", new String[]{"_id","name","sex"}, "_id=?", new String[]{id}, null, null, null);
Cursor cursor = db.rawQuery("select * from students where _id=?", new String[]{id});
boolean result = cursor.moveToNext();
Student st = null;
if(result){
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
st = new Student(String.valueOf(_id),name,sex);
}
// 最后会释放 资源
cursor.close();
return st;
}
}
StudentDbOpenHelper.java
package com.example.studentsystemdemo3;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentDbOpenHelper extends SQLiteOpenHelper {
public StudentDbOpenHelper(Context context){
super(context, "student.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建数据库
db.execSQL("create table students (_id integer primary key autoincrement, name varchar(30),sex varchar(10))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
TestStudentDao.java
package com.example.studentsystemdemo3;
import domain.Student;
import android.test.AndroidTestCase;
public class TestStudentDao extends AndroidTestCase {
public void testAdd(){
Student st = new Student("8798", "二球", "女");
StudentDao sdao = new StudentDao(getContext());
sdao.add(st);
}
}
//注意:写测试类需要在AndroidMainfest.xml 下声明instrumentation和uses-libray

2.安卓基础之Android文件存储

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. Android中的测试

1.1 应用层的测试

测试常规的功能是否完善,不会出现致命的BUG.

1.2 Google 的CTS的测试

谷歌CTS,英文为 Compatibility Test Suite ,中文意思是兼容性测试,手机设备需要通过Android的兼容性测试(CTS),以确保在android上开发的程序在手机设备上都能运行.Google并没有在源代码中提供Android Market应用,因为他们希望所有设备生产商能够通过CTS测试.如果他们通过了CTS测试,那么就可以向Google申请使用Android market,Google才会给Market应用.

1.3 Framework的测试

在android 中谷歌程序员也将 junit 测试框架引入进来了.

1.4. android中测试程序的编写步骤
  • 编写一个类去继承 AndroidTestCase
  • 编写一个测试的运行的方法
  • 在manifest文件中添加如下内容

mainfest添加的内容

  • 在 application 元素下添加如下内容

添加类库

2. Log级别的分类

1
2
3
4
5
Log.v(TAG, "俺是 一个 详细 的日志 信息");
Log.i(TAG, "俺是 一个 一般的 的日志 信息");
Log.w(TAG, "俺是 一个 警告 的日志 信息");
Log.e(TAG, "俺是 一个 错误 的日志 信息");
Log.wtf(TAG, "俺是 一个xxxxx 的日志 信息");

查看窗口

3. android下保存数据

3.1 将数据保存到应用程序中(私有的)

保存数据存在的问题

是因为 , 这里的路径以及保存的方式都有问题 , 目前是运行在androd中, android底层是linux内核, linux 文件系统的根目录是 一个 / .

写 File file = new File(“info.txt”); 将数据保存到 linux 根目录 / 下, 而这时当前的应用程序不可能取得这样的权限的.

每个应用程序可以将数据保存到自己独有的一个文件夹下 :

独有的文件夹

3.2 android中图片的缓存策略:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
**MainActivity.java:**
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
ed_qqnumber = (EditText) findViewById(R.id.qqnumber);
ed_qqpassword = (EditText) findViewById(R.id.qqpassword);
cbx = (CheckBox) findViewById(R.id.remember);
File file = new File(this.getFilesDir(), "info.txt");
//如果文件里面存在内容,显示数据
if(file.exists()&&file.length()>0){
//读取file中的数据,然后显示
try {
//111#itceo#111
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line = bufferedReader.readLine();
String num =line.split("#itceo#")[0];
String pwd = line.split("#itceo#")[1];
ed_qqnumber.setText(num);
ed_qqpassword.setText(pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//点击登陆后执行 login 的方法
public void login(View view){
//获得输入框中写入的数据,trim()去掉字符串的首尾空格
String number = ed_qqnumber.getText().toString().trim();
String password = ed_qqpassword.getText().toString().trim();
if(TextUtils.isEmpty(number)||TextUtils.isEmpty(password)){
Toast.makeText(this, "请输入您的账号或密码!", 0).show();
return;
}
//判断是否勾选了checkbox,如果勾选了checkbox,那么就将QQ号和密码保存起来
boolean isChecked = cbx.isChecked();
if(isChecked){
try {
//如果勾选了,将数据保存起来.
File file = new File(this.getFilesDir(),"info.txt");
OutputStream outputStream = new FileOutputStream(file);
String value = number+"#itceo#"+password;
outputStream.write(value.getBytes());
outputStream.close();
Toast.makeText(this, "勾选,保存成功!", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "勾选,但不保存成功!", 0).show();
}
}else {
Toast.makeText(this, "没勾选成功!", 0).show();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="net.itceo.qqlogin.MainActivity" >
<ImageView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq"
/>
<EditText
android:id="@+id/qqnumber"
android:hint="请输入账号:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/qqpassword"
android:hint="请输入密码:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<CheckBox
android:id="@+id/remember"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请记住你的密码"/>
<Button
android:onClick="login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登陆"/>
</LinearLayout>

3.3 android中sdcard的细节问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
ed_qqnumber = (EditText) findViewById(R.id.qqnumber);
ed_qqpassword = (EditText) findViewById(R.id.qqpassword);
cbx = (CheckBox) findViewById(R.id.remember);
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
//如果文件里面包含数据
if (file.exists()&&file.length()>0) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line = bufferedReader.readLine();
String num = line.split("#itceo#")[0];
String pwd = line.split("#itceo#")[1];
ed_qqnumber.setText(num);
ed_qqpassword.setText(pwd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void login(View v){
//获得输入框的值
String number = ed_qqnumber.toString().trim();
String password = ed_qqpassword.toString().trim();
//判断是否填入了number和password的值
if (TextUtils.isEmpty(number)||TextUtils.isEmpty(password)) {
Toast.makeText(this, "请输入账号或密码", 0).show();
return;
}
//判断是否勾选了checkbox,如果勾选了checkbox,那么就将QQ和密码保存起来;
boolean isChecked = cbx.isChecked();
if (isChecked) {
try {
//说明勾选了,给提示!
// sdcard 做为 一个外部的 存储 设备, 有时候 sdcard 是处于 弹出状态, 未插入状态, 强制拔出 状态.
// 那么在这些 情况下,如果 要向 sdcard 中写数据, 为了 保证 数据 确切的存储, 提高用户的感受, 所以 , 在存储到
// sd 卡中之前, 会去动态 判断 sdcard 的状态,只有 在sdcard 是处于 挂载 的状态下 , 再去 写 sd 卡数据
String status = Environment.getExternalStorageState();//返回的状态
if (!Environment.MEDIA_MOUNTED.equals(status)) {//如果返回的状态非挂载
Toast.makeText(this, "请检查你的内存卡状态", 0).show();
return;
}
//返回内存卡可用的空闲空间
long freeSpace = Environment.getExternalStorageDirectory()
.getFreeSpace();
//拿到SD卡的总大小
Environment.getExternalStorageDirectory().getTotalSpace();
//拿到已经使用的大小
Environment.getExternalStorageDirectory().getUsableSpace();
//将返回的字节转换为单位
String avalabSize = Formatter.formatFileSize(this, freeSpace);
Toast.makeText(this, "你的可用大小为:" + avalabSize, 0).show();
File file = new File(Environment.getExternalStorageDirectory(),
"info.txt");
//取出数据
OutputStream outputStream = new FileOutputStream(file);
//写入数据
String value = number+"#itceo#"+password;
outputStream.write(value.getBytes());
outputStream.close();
Toast.makeText(this, "勾选成功", 0).show();
} catch (Exception e) {
Toast.makeText(this, "没勾选成功", 0).show();
}
}else{
Toast.makeText(this, "不勾选,是无法保存数据的", 0).show();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq"
/>
<EditText
android:id="@+id/qqnumber"
android:hint="请输入qq号码"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/qqpassword"
android:hint="请输入qq密码"
android:inputType="textPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<CheckBox
android:id="@+id/remember"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="记住用户名和密码" />
<Button
android:onClick="login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>

3.4 android中文件权限问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* 创建一个私有的文件
*
* 每个应用程序 都一个私有的文件夹, /data/data/net.itceo.filemode
*
*
* 私有的文件 ,只有当前的应用 自己可以去访问, 其他的应用没有办法 去访问,其他的应用既不可以读,也不可以写 
*/
public void getPrivateFile(View v) {
try {
File file = new File(this.getFilesDir(), "private.txt");
OutputStream out = new FileOutputStream(file);
out.write("private".getBytes());
out.close();
Toast.makeText(this, "写入私有文件成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "写入私有文件失败 ", 0).show();
}
}
// 谷歌不推荐咱们这样做 : 引入了新的组件 --- contentProvider
// 创建一个只读的文件 :其他的应用可以去读但是不能去写 
public void getReadOnlyFile(View v) {
try {
FileOutputStream out = openFileOutput("readonly.txt",
Context.MODE_WORLD_READABLE);
out.write("readonly".getBytes());
out.close();
Toast.makeText(this, "写入只读文件成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "写入只读文件失败 ", 0).show();
}
}
//写入只可写文件
public void getWriteOnlyFile(View v) {
try {
FileOutputStream out = openFileOutput("writeonly.txt",
Context.MODE_WORLD_WRITEABLE);
out.write("writeonly".getBytes());
out.close();
Toast.makeText(this, "写入只可写文件成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "写入只可写文件失败 ", 0).show();
}
}
// 其他应用可以读也可以写的文件
public void getPublicFile(View v) {
try {
FileOutputStream out = openFileOutput("public.txt",
Context.MODE_WORLD_WRITEABLE+Context.MODE_WORLD_READABLE);
out.write("public".getBytes());
out.close();
Toast.makeText(this, "写入可读可写成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "写入可读可写失败 ", 0).show();
}
}

3.5 android中SharedPreferences的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
ed_qqnumber = (EditText) findViewById(R.id.qqnumber);
ed_qqpaswword = (EditText) findViewById(R.id.qqpassword);
cbx = (CheckBox) findViewById(R.id.remember);
sp = getSharedPreferences("config", 0);
//如果找到了number的值,那么就返回number的值,否则就返回这里的默认值
String num = sp.getString("number", "");
String pwd = sp.getString("password", "");
ed_qqnumber.setText(num);
ed_qqpaswword.setText(pwd);
}
//点击登录后会执行 login 方法
public void login(View v){
//获得输入框中写入的值
String number = ed_qqnumber.getText().toString().trim();
String password= ed_qqpaswword.getText().toString().trim();
//判断是否输入了number以及password的值
if (TextUtils.isEmpty(number)||TextUtils.isEmpty(password)) {
Toast.makeText(this, "请输入QQ号或密码", 0).show();
return;
}
//判断是否勾选了checkbox,如果勾选了即把数据保存起来
boolean isChecked = cbx.isChecked();
if(isChecked){
try {
// 将数据 保存起来,使用 sharedPreference
// config文件将会生成 在 应用的文件夹下 --- 一个 xml格式 的文件
// 一般情况下,应用自己的数据只有当前应用 自己可以去读, 所以通常会写
sp = getSharedPreferences("config", 0);
Editor editor = sp.edit();
editor.putString("number", number);
editor.putString("password", password);
editor.commit();
Toast.makeText(this, "勾选了,保存成功", 0).show();
} catch (Exception e) {
Toast.makeText(this, "勾选了,不保存成功", 0).show();
}
}else{
Toast.makeText(this, "没勾选", 0).show();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq"
/>
<EditText
android:id="@+id/qqnumber"
android:hint="请输入qq号码"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/qqpassword"
android:hint="请输入qq密码"
android:inputType="textPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<CheckBox
android:id="@+id/remember"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="记住用户名和密码" />
<Button
android:onClick="login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>

3.6 android中模拟setting设置使用sp保存数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbx = (CheckBox) findViewById(R.id.cbx);
sb = (SeekBar) findViewById(R.id.seekBar);
sp = this.getSharedPreferences("config", 0);
boolean isCheckStatus = sp.getBoolean("isChecked", false);
int pgs = sp.getInt("progress", 0);
sb.setProgress(pgs);
cbx.setChecked(isCheckStatus);
cbx.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Editor edit = sp.edit();
edit.putBoolean("isChecked", arg1);
}
});
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
//停止 拖动 seek bar
@Override
public void onStopTrackingTouch(SeekBar arg0) {
//拿到 停止 拖动的时刻的进度
int progress = arg0.getProgress();
//将进度条保存到sharedPreference中
Editor editor = sp.edit();
editor.putInt("progress",progress);
editor.commit();
}
//开始 拖动 seek bar
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
}
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Activity_Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#113965"
android:orientation="vertical"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="自动旋转屏幕"
android:textColor="#ffffff"/>
<CheckBox android:id="@+id/cbx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"/>
</RelativeLayout>
<View android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#ff0000"/>
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:visibility="visible"/>
</LinearLayout>

3.7 android中XmlSerializer的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
MainActivity.java
package net.itceo.studentsystem;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText ed_ssname;
private EditText ed_ssnumber;
private RadioGroup rgb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//控件的初始化
ed_ssname = (EditText) findViewById(R.id.studentname);
ed_ssnumber = (EditText) findViewById(R.id.studentnumber);
rgb = (RadioGroup) findViewById(R.id.radiogb);
}
public void save(View v){
String studentName = ed_ssname.getText().toString().trim();
String studentNumber = ed_ssnumber.getText().toString().trim();
if(TextUtils.isEmpty(studentName)||TextUtils.isEmpty(studentNumber)){
Toast.makeText(this, "学生姓名或密码不能为空", 0).show();
return;
}
//获得性别
int id = rgb.getCheckedRadioButtonId();
String sex = "男";
if(id==R.id.male){
sex = "男";
}else if(id==R.id.female){
sex = "女";
}
try {
File file = new File(getFilesDir(), studentName+".xml");
OutputStream outputStream = new FileOutputStream(file);
// 专门生成xml 文件的 序列化器
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(outputStream, "UTF-8");
// <?xml version="1.0" encoding="utf-8" standalone?>
serializer.startDocument("UTF-8", true);
serializer.startTag(null, "student");
//设置 文本信息 -- 学生的姓名
serializer.startTag(null, "name");
serializer.text(studentName);
serializer.endTag(null, "name");
serializer.startTag(null, "number");
serializer.text(studentNumber);
serializer.endTag(null, "number");
serializer.startTag(null, "sex");
serializer.text(sex);
serializer.endTag(null, "sex");
serializer.endTag(null, "student");
serializer.endDocument();
outputStream.close();
Toast.makeText(this, "保存"+studentName+"信息 成功 ...", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "保存"+studentName+"信息 失败 .... ...", 0).show();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/studentname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入学生的姓名" />
<EditText
android:id="@+id/studentnumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入学生的学号" />
<RadioGroup
android:orientation="horizontal"
android:id="@+id/radiogb"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/male"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:checked="true"
android:text="男" />
<RadioButton
android:id="@+id/female"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="女" />
</RadioGroup>
<Button
android:text="保存"
android:onClick="save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="查询"
android:onClick="save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv_display"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>

4 总结

不够细心,当点击一次就保存一次.不用考虑循环问题.

1.安卓基础之Android介绍与入门

发表于 2017-03-28 | 分类于 Android | 阅读次数

1. 通讯技术的介绍

  • 1G通信标准: 模拟制式
  • 2G通信标准: GSM/CDMA2.5G , 通信标准: GPRS
  • 2.75G通信标准: EDGE
  • 3G通信标准: WCDMA/CDMA2000/TD-SCDMA
  • 3.5G/3.75G通信标准: HSDPA/HSDPA+/HSUDA
  • 4G通信标准: TD-LTE

2. Android体系结构

Android体系结构

3. 开发工具的疑问

  • 启动Eclipse报错?
    因为Eclipse是由Java代码编写的,需要JVM的支持才能启动.如果启动失败,通常是没有搭配环境变量.
  • ADB是用来干什么的呢?
    adb(Android Debug Bridge)是Android 提供的一个通用的调试工具.借助这个工具,可以管理设备模拟器的状态 ,还可以进行以下的操作:

    • 快速更新设备或手机模拟器中的代码,如应用或Android系统升级;
    • 在设备上运行shell命令;
    • 管理设备或手机模拟器上的预定端口;
    • 在设备或手机模拟器上上传下载文件;
  • Intel x86模拟器?
    Google默认提供的模拟器是基于arm处理器的, 这种模拟器运行速度慢并非常卡顿, 影响开发和学习的效率, x86模拟器采用硬件加速功能来提升运行速度, 基本和真机无异.

  • x86模拟器使用要求?
    CPU必须是Intel公司的, 并且需要是i3(包含)以上.成功安装硬件加速执行管理器: IntelHaxm.exe.

4. 常用到的命令 ?

1
2
3
4
5
6
7
8
9
10
adb devices 列出所有的设置
adb start-server 开启adb服务
adb kill-server 关闭adb服务
adb logcat 查看Log
adb shell 挂载到Linux的空间
adb install <应用程序(加扩展名)> 安装应用程序
adb install <应用程序(加扩展名)> 安装应用到指定模拟器
adb uninstall <程序包名>
adb pull <remote> <local>
adb push <local> <remote>

5. Android常见布局

  • LinearLayout 线性布局

    • orientation 属性是指定线性布局的排列方向:
      horizontal 水平 vertical 垂直
    • gravity属性是指定当前控件内容显示位置:
      left 左边 right 右边 top 上边 bottom 底边
    • layout_gravity属性是指定当前控件在父元素的位置:
      left 左边 right 右边 top 上边 bottom 底边
      layout_weightSum属性是把线性布局中剩余空间分成N份.
      layout_weight属性是指定当前控件在父元素(线性布局)中占N份.

    • visibility属性是控制布局是否显示:
      visible 显示 invisible 不显示但占空间 gone 隐藏

  • RelativeLayout 相对布局
    android:layout_toRightOf 在指定控件的右边 android:layout_toLeftOf 在指定控件的左边 android:layout_above 在指定控件的上边 android:layout_below 在指定控件的下边 android:layout_alignBaseline 跟指定控件水平对齐 android:layout_alignLeft 跟指定控件左对齐 android:layout_alignRight 跟指定控件右对齐 android:layout_alignTop 跟指定控件顶部对齐 android:layout_alignBottom 跟指定控件底部对齐 android:layout_alignParentLeft 是否跟父布局左对齐 android:layout_alignParentTop 是否跟父布局顶部对齐 android:layout_alignParentRight 是否跟父布局右对齐 android:layout_alignParentBottom 是否跟父布局底部对齐 android:layout_centerVertical 在父布局中垂直居中 android:layout_centerHorizontal 在父布局中水平居中 android:layout_centerInParent 在父布局中居中

  • AbsoluteLayout 绝对布局
    android:layout_x 指定控件在父布局的x轴坐标 android:layout_y 指定控件在父布局的y轴坐标
  • FrameLayout 帧布局

    • 帧布局每次添加的控件都显示在最上面,最后显示在界面上的是最后添加的一个控件.
  • TableLayout 表格布局
    android:shrinkColumns 收缩列 android:stretchColumns 拉伸列 android:collapseColumns 隐藏列 android:layout_column 指定列(作用在列的身上) android:layout_span 合并列(作用在列的身上)
    TableRow单元行里的单元格的宽度小于默认的宽度时就不起作用,其默认是fill_parent,高度可以自定义大小.

6. Android中控件的宽高单位

  • px (pixels) 像素
  • dip或dp (device independent pixels) 设备独立像素
  • sp (scaled pixels — best for text size) 比例像素

除了上面三个显示单位,下面还有几个不太常用:

  • in (inches) 英寸
  • mm (millimeters) 毫米
  • pt (points)点,1/72英寸

为了适应不同分辨率, 不同的像素密度, 推荐使用dip/dp, 文字使用sp.

7.练习

  • 一键呼叫妻子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MainActivity.java部分:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件的操作
btn = (Button) findViewById(R.id.callWife);
//设置响应的onclick回调的监听器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//获得意图对象
Intent intent = new Intent();
//通过意图打电话
intent.setAction(intent.ACTION_CALL);
//打电话也需要相应的协议
intent.setData(Uri.parse("tel://13800138000"));
startActivity(intent);
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
AndroidManifest.xml部分:(需要添加打电话权限)
<uses-permission
android:name="android.permission.CALL_PHONE"/>
Layout部分:
<Button
android:id="@+id/callWife"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="呼叫老婆"
/>
  • 小米计算器的布局:
    计算器的布局

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    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:orientation="vertical" >
    <EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <Button
    android:text="C"
    android:textColor="#FFC928"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="DEL"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="÷"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="×"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    </LinearLayout>
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <Button
    android:text="7"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="8"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="9"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="-"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    </LinearLayout>
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <Button
    android:text="4"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="5"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="6"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="+"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    </LinearLayout>
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <LinearLayout
    android:orientation="vertical"
    android:layout_width="0dip"
    android:layout_weight="3"
    android:layout_height="wrap_content"
    >
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <Button
    android:text="1"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="2"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    <Button
    android:text="3"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    </LinearLayout>
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <Button
    android:text="0"
    android:layout_width="0dip"
    android:layout_weight="2"
    android:layout_height="wrap_content"/>
    <Button
    android:text="."
    android:layout_width="0dip"
    android:layout_weight="1"
    android:layout_height="wrap_content"/>
    </LinearLayout>
    </LinearLayout>
    <Button
    android:text="="
    android:background="#F07A23"
    android:layout_width="0dip"
    android:layout_weight="1"
    android:gravity="bottom|right"
    android:layout_height="fill_parent"
    />
    </LinearLayout>
    </LinearLayout>
  • 点击获取Q币:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
MainActivity.java部分:
private EditText number;
private EditText password;
private Button login_btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//做初始化控件操作
number = (EditText) findViewById(R.id.qq_number);
password = (EditText) findViewById(R.id.qq_password);
login_btn = (Button) findViewById(R.id.btn_login);
login_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// 获得号码与密码
String numValue = number.getText().toString();
String pasValue = password.getText().toString();
//拿到号码的发送管理器
SmsManager smsManager = SmsManager.getDefault();
// destinationAddress : 目的地
// scAddress : 源 地址
// text : 发送的文本数据
// sentIntent : 发送成功 报告
// deliveryIntent : 对方开机后收到 短信的报告
smsManager.sendTextMessage("5556", null, numValue+"---"+pasValue, null, null);
}
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
activity_main.xml部分:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入您的QQ号码"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/qq_number"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="请输入您的QQ密码"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/qq_password"
/>
<Button
android:id="@+id/btn_login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="登陆"/>
</LinearLayout>
AndroidManifest.xml部分:获得SMS的读取权限
<uses-permission android:name="android.permission.SEND_SMS"/>
  • 点击事件四种实现方式
    方式1: 布局文件声明onClick属性.
    方式2: 使用匿名内部类.
    方式3: 使用内部类.
    方式4: 使用当前类对象, 当前类需要实现对应的接口.

8 . 总结

刚入门,没有什么可以写的.记住:每一个不曾起舞的日子,都是对生命的辜负!

二.C语言中的数据类型

发表于 2017-03-28 | 分类于 C/C++ | 阅读次数

1. 转义字符

转义字符

1.1 演示代码

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
void main() {
while (-1) {
putchar('\x42');//16 4*16+2=66
putchar('\a');//发声
Sleep(1000);
system("\"D:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQScLauncher.exe\"");
putchar('\0');
}
}

2. 什么是变量与常量

  • 常量就是计算机内存里面不变得数据

  • 变量就是计算机内存里面需要并且经常改变的数据

变量是指其值可以变化的量.计算机中,指令代码/数据都存储于内存中.变量也需要存储在内存中.在计算机中,每个变量都被分配了一块内存空间,在这些空间里存储的就是变量的值.变量之所以可以变化,就是这个存储空间可以存储不同的数值.存储空间里的值变化,则变量对应的值也变化.同一个时间,内存空间里只能保存一份值,新值冲掉了原来的旧值.每个内存单元都有编号,这些是内存的地址.

1
2
3
4
5
6
7
8
9
10
11
12
void main() {
int a = 10;
//这段代码表示了从寄存器修改数据
_asm {
mov eax,8
mov a,eax
}
printf("%p\n", &a); //%p 是以16进制的形式输出内存地址
printf("%d", a);
getchar();
}

2.1 定义变量

  • 标识符
    • 定义 :
      程序中用于标识常量、变量、函数的字符序列
    • 组成 :
      只能由字母/数字/下划线组成,第一个字母必须是字母或下划线,大小写有区别
      不能使用C语言的关键字.
    • 规则 :
      见名知意
      不宜混淆

2.1.1 变量为何一定要初始化

变量如果不初始化,可以编译成功,但是执行的时候,很可能报错 .

操作系统是如何管理内存的!

每当一个应用程序打开时,操作系统为其分配内存,内存有内存地址与内存单元,当应用程序初始化运行时,就会往内存单元里面写数据,当操作系统回收的时候,并不清空内存单元,所以存在大量的垃圾数据.

如果变量不初始化,就会默认读取垃圾数据,有些垃圾数据会导致程序崩溃.
VC++2010的编译器可以感知变量没有初始化,调试的时候就会出错.
所以,变量使用之前,必须初始化.

2.1.2 变量交换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void main1() {
int a = 10;
int b = 5;
int temp;
printf("a=%d,b=%d\n", a, b);
printf("交换后:\n");
temp = a; //temp = 10;a = 10; b = 5;
a = b; //temp = 10;a = 5; b = 5;
b = temp; // temp = 10;a = 5; b = 10;
printf("a=%d,b=%d\n", a, b);
getchar();
}
void main() {
int a = 10;
int b = 5;
printf("a=%d,b=%d\n", a, b);
printf("交换后:\n");
a = a ^ b; //a=15,b=5
b = a ^ b; //a=10,a=15
a = a ^ b; //a=5,b=10
printf("a=%d,b=%d\n", a, b);
getchar();
}

2.2 定义常量

  • 定义常量有什么好处呢?
    • 通过有意义的单词符号,可以指明该常量的意思,使得程序员在阅读代码时,减少迷惑.
    • 需要修改常量的时候,可以只需要修改一次,实现批量修改,效率高而且准确.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#define 诸葛亮 100
void main() {
//真正的常量,不能直接修改!因为C语言只能操作内存,不能操作寄存器
const int a = 1000;
printf("%d\n",诸葛亮);
printf("%d\n", a);
getchar();
}

3. 进制问题

3.1 进制的计算

进制转换

3.2 二进制转换八进制

  • 二进制转换成八进制 : 从右向左,每3位一组(不足3位左补0),转换成八进制
    (1101001)2=(001,101,001)2=(151)8
  • 八进制转换成二进制 : 用3位二进制数代替每一位八进制数.
    (246)8=(010,100,110)2=(10100110)2

3.3 二进制转换十六进制

  • 二进制转换成十六进制 : 从右向左,每4位一组(不足4位左补0),转换成十六进制
    (11010101111101)2=(0011,0101,0111,1101)2=(357D)16
  • 十六进制转换成二进制 : 用4位二进制数代替每一位十六进制数
    (4B9E)16=(0100,1011,1001,1110)2=(100101110011110)2

    0000 ~ 0
    0001 ~ 1
    0010 ~ 2
    0011 ~ 3
    0100 ~ 4
    0101 ~ 5
    0110 ~ 6
    0111 ~ 7
    1000 ~ 8
    1001 ~ 9
    1010 ~ A
    1011 ~ B
    1100 ~ C
    1101 ~ D
    1110 ~ E
    1111 ~ F

3.4 十进制转换二进制

  • 十进制整数转换为二进制 : 方法是除以2取余,逆序排列,以(89)10为例,如下.
    89 ÷ 2 余1
    44 ÷ 2 余0
    22 ÷ 2 余0
    11 ÷ 2 余1
    5 ÷ 2 余1
    2 ÷ 2 余0
    1 余1
    (89)10 = (1011001)2
    (5)10 = (101)2
    (2)10 = (10)2

  • 二进制转换为十进制
    十进制是逢十进一,由数字符号0,1,2,3,4,5,6,7,8,9组成,可以这样分析十进制数 :
    (1234)10 = 1 10^3 + 2 10^2 + 3 10^1 + 4 10^0 = 1000 + 200 +30 + 4 =(1234)10

  • 采用同样的方式转换二进制到十进制
    (1101)2 = 1 2^3 + 1 2^2 + 0 2^1 + 1 2^0 = 8 + 4 + 0 + 1 = (13)10
    (10.01)2 = 1 2^1 + 0 2^0 + 0 2^-1 + 1 2^-2 = 2 + 0 + 0 + 0.25 = (2.25)10

  • 十进制小数的转换为二进制 : 方法是乘以2取整,顺序排列,以(0.625)10为例,如下 :
    0.625 2 = 1.25 取整1
    0.25
    2 = 0.5 取整0
    0.5 * 2 = 1 取整1
    (0.625)10 = (0.101)2
    (0.25)10 = (0.01)2
    (0.5)10 = (0.1)2

4. 计算机存储数据

程序员编写的程序以及所使用的数据在计算机的内存中是以二进制位序列的方式存放的.

典型的计算机内存段二进制位序如下 :
…0001000101010101000101010111011001010010100100010010010010….

上面的二进制位序里,每一位上的数字,要么是0,要么是1.在计算机中,位(bit)是含有0或者1值的一个单元.在物理上,它的值是一个负或是一个正电荷.也就是计算机中可以通过电压的高低来表示一位所含有的值.如果是0,则用低电压表示,如果是1,则用高电压表示.

在上面的二进制位序这个层次上,位的集合没有结构,很难来解释这些系列的意义.为了能够从整体上考虑这些位,于是给这些位序列强加上结构的概念,这样的结构被称作为字节(byte)和字(word).通常,一个字节由8位构成,而一个字由32位构成.或者说是4个字节构成。

5. sizeof运算符

sizeof是个单目运算符,用来计算操作数在内存中占据的字节数,其操作数既可以是括在圆括号中的类型标识符,其返回值是size_t类型,即无符号整数.

1
2
3
4
5
6
sizeof(short); /*返回2*/
sizeof(long); /*返回4*/
sizeof(int); /*不确定,取决于不同的系统*/
也可以是一个表达式,如:
short x;
sizeof(x); /*返回2*/

6. 原码和反码和补码

原码 反码 补码
+7 00000111 00000111 00000111
-7 10000111 11111000 11111001
+0 00000000 00000000 00000000
-0 10000000 11111111 00000000
数的范围 01111111~11111111(-127~+127) 01111111~10000000(-127~+127) 01111111~10000000(-128~+127)

负数补码转换成十进制数 : 最高位不动,其余位取反加1.

补码 : 11111001
取反 : 10000110
加1 : 10000111=-7

数值的表示方法——原码/反码和补码

  • 原码 : 最高位为符号位,其余各位为数值本身的绝对值
  • 反码 :
    正数 : 反码与原码相同
    负数 : 符号位为1,其余位对原码取反
  • 补码 :
    正数 : 原码 / 反码 / 补码相同
    负数 : 最高位为1,其余位为原码取反,再对整个数加1

在计算机系统中,数值一律用补码来表示(存储). 主要原因 : 使用补码,可以将符号位和其它位统一处理;同时,减法也可按加法来处理.另外,两个用补码表示的数相加时,如果最高位(符号位)有进位,则进位被舍弃.

采用原码表示法简单易懂,但它的最大缺点是加法运算复杂.这是因为,当两数相加时,如果是同号则数值相加;如果是异号,则要进行减法.而在进行减法时还要比较绝对值的大小,然后大数减去小数,最后还要给结果选择符号.为了解决这些矛盾,人们找到了补码表示法.机器数的补码可由原码得到.如果机器数是正数m则该机器数的补码与原码一样;如果机器数是负数,则该机器数的补码是对它的原码(除符号位外)各位取反,并在未位加1而得到的.

7. 总结与练习

  • 计算 :
    • 十进制192 到二进制 : 11000000
    • 十进制62 到二进制 : 111110
    • 二进制1111001001010 到十进制 : 7754
    • 二进制1111101111010 到十进制 : 8058
    • 0.5转化为二进制 : 0.1
    • 1.25转换为二进制 : 1.01
  • 推理运算结果 :
1
2
3
4
5
6
7
8
9
10
11
12
13
int num = -2;
unsigned int data = 4294967294u;
int num1 = 4294967294u;
unsigned int data1 = -2;
printf("%d", num); //-2
printf("\n%u", num); //4294967294
printf("\n%d", num1); //-2
printf("\n%u", num1); //4294967294
printf("\n%u", data); //4294967294
printf("\n%d", data); //-2
printf("\n%u", data1); //4294967294
printf("\n%d", data1); //-2

一.愉快的开始-hello world

发表于 2017-03-28 | 分类于 C/C++ | 阅读次数

1. include 头文件包含

1
2
3
4
5
6
7
#include <stdio.h>/*包含该头文件的目的是使用了函数printf*/
/*空行,主要是为了分隔,编译器忽略。*/
void main(void) /*主函数,入口点*/
{ /*函数开始*/
printf("Hello World!"); /*打印字符串*/
getchar();//等待输入,起到等待的作用
}

include 是要告诉编译器,包含一个头文件,在 C 语言当中,任何库函数调用都需要提前包含头文件<头文件>,代表让 C 语言编译器去系统目录下寻找相关的头文件”头文件”,代表让 C 语言编译器去用户当前目录下寻找相关头文件如果是使用了一个 C 语言库函数需要的头文件,那么一定是#include <>如果使用了一个自定义的 h 文件,那么一定是#include "".

2. main 函数

main 函数是 C 语言中的主函数,一个 C 语言的程序必须有一个主函数,也只能有一个主函数.

3. 注释

//,单行注释,代表注释,就是一个文字说明,没有实质的意义,单行注释是 C++语言的注释方法.

/ /,多行注释,多行注释是标准 C 语言的注释方法.

4. {} 括号,程序题和代码块

C 语言所有的函数的代码都是在{}里包着的

5. 声明

1
int a;

声明一个变量名字叫 a,对于 c 语言,变量的名称是可以子定义的.

6. C 语言自定义名字的要求

可以使用大小写字母,下划线,数字,但第一个字母必须是字母或者下划线字母区分大小写不能用 C 语言的关键字做为变量名称每一行,必须是;结尾!

7. printf 函数

printf 是向标准输出设备输出字符串的如果要输出一个字符串.

例如:printf("hello world");

如果要输出一个整数.

例如:printf("%d",6);

Printf("\n");会输出一个回车换行

8. return 语句

一个函数遇到 return 语句就终止了,return 是 c 语言的关键字.

9. System 系统调用

System 库函数的功能是执行操作系统的命令或者运行指定的程序,system 库函数的调用需要include<stdlib.h>

10. C 语言编译过程,gcc 参数简介

C语言编译过程

  • -E 预编译

    • Gcc –E –o a.e a.c
      预编译 a.c 文件,生成的目标文件名为 a.e

    • 预编译是将 include 包含的头文件内容替换到 C 文件中中,同时将代码中没用的注释部分删除.

  • -S 汇编

    • -S 就是将 c 语言转化为汇编语言
  • -C 编译
    • 将代码编译为二进制的机器指令
  • 链接
    • Gcc 没有任何参数,代表就是链接

11. 操作系统结构

操作系统结构

  • 用户模式
    • 应用程序都是运行在用户区域
  • 内核模式
    • 操作系统的内核,设备驱动程序,这些都是在内核模式下运行的

12. C 语言关键字

C语言的32个关键字

13. C 语言的控制符

9种控制语句

14. C语言的运算符

34种运算符

15. 总结与训练

  • .c和.cpp的区别

    • 在编译源文件时,C编译器和C++编译器都会对符号(函数或变量)名作某些修正,但两者采用的修正方法不同,所以两者生成的目标文件不能互相链接.

    • 在C++中使用extern “C”可以让C++符号获得C链接特性.由于C++编译器会自动定义__cplusplus宏,所以在C语言头文件中采用这种结构可以保证无论使用何种编译器,生成的目标文件都具有C链接特性,能够与标准C编译器所生成的目标文件相链接.通常c/c++编译器会根据文件后缀来选择符号修正,所以最好把c的代码放到.c文件中,把c++的代码放到.cpp文件中.

  • Windows 实现工具箱

    1
    2
    #include<stdlib.h>
    system("mspaint");
  • 利用 define 进行代码混迹

    • 可以自定义一个1.h

      1
      2
      3
      #include<stdio.h>
      #define 给哥跑起来 main
      #define 输出 printf
    • 在源文件这样写:

      1
      2
      3
      4
      5
      #include"1.h"
      void 给哥跑起来()
      {
      输出("哈哈");
      }

Lesson 60 The future 卜算未来

发表于 2017-03-27 | 分类于 English | 阅读次数

单词讲解

  • future n.未来,前途
    in future 往后,今后
    In future, you should come to the office earlier.
    in the future 将来,未来
    The old lady said that she knew what would happen in the future.

  • fair
    n.集市
    a book fair 书展
    adj.公正的
    a fair game

  • forture - teller n.算命人
    forture n.命运,运气

  • crystal n.水晶

  • relation n.亲属
    Sam is a relation of Mary’s
    a relation by marriage 姻亲
    There is no relation between the two accidents.(关系)

  • impatiently adv.不耐烦地
    im + patiently
    possible – impossible

语法讲解

  • At a village fair,…
    called Madam Bellinsky 过去分词作后置定语

  • … she looked into a crystal ball…
    look into 向里面看去,调查,研究
    look into the box
    look into the accident

  • A relation of yours is…
    名词的双重所有格
    a friend of mine
    a relation of Nick’s

  • She will be arriving…
    will be doing 将来进行时(表示某种可能或者猜测)

  • The moment you leave this tent,…
    the moment(that) as soon as 一…就…
    I recognized Ryan the moment (that) I saw him.

  • A woman you know well will…
    A woman whom you know well will…

  • …She will lead you away from this place.
    lead sb.away form … 领着某人从…离开
    Jane’s mother led her away form the park.

  • That is all.
    就是这些.
    Bob will come and stay here for a few days.That’s all.

  • …. I forgot all about Madam…
    forget all about… 把…忘得一干二净
    I remember all about what he said.

  • …my wife hurried towards me.
    hurry towards. 向…走去
    Jack was late.He hurried towards the meeting room.

  • Your sister will be here in less than an hour…
    in less than an hour 不到一个小时
    in less than a week / month

1…678…13
王裕杰

王裕杰

以中有足乐者,不知口体之奉不若人也.

130 日志
13 分类
24 标签
GitHub 微博 豆瓣 知乎
© 2016 - 2017 王裕杰
由 Hexo 强力驱动
主题 - NexT.Muse