[1].ProgressBar
 
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
int progress = progressBar.getProgress();
progress = progress + 10;
progressBar.setProgress(progress);
 
使用setVisibility()方法,可以传入 View.VISIBLE、View.INVISIBLE 和 View.GONE,控制可见性。
使用max设置最大值。通过 style 属性可以将它指定成水平进度条.
 
【2】AlertDialog
 
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("This is Dialog");
dialog.setMessage("Something important.");
dialog.setCancelable(false);//可否取消
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {//确定按钮的点击事件
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {//取消按钮的点击事件
@Override
public void onClick(DialogInterface dialog, int which) {
 
}
});
dialog.show();
 
【3】ProgressDialog
 
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("This is ProgressDialog");
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
ProgressDialog.dismiss();
 
[4].引入布局
 
<include layout="@layout/title" />
 
【5】自定义布局
 
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked Edit button",Toast.LENGTH_SHORT).show();
}
});
 
layout布局里:
<com.example.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
></com.example.uicustomviews.TitleLayout>
 
【6】listview
 
(1)定义一个实体类,作为 ListView 适配器的适配类型。新建类 Fruit,代码如下所示:
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
(2)为 ListView 的 子 项 指 定 一 个 我 们 自 定 义 的 布 局
(3)接下来需要创建一个自定义的适配器
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
public FruitAdapter(Context context, int textViewResourceId,List<Fruit> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
//一般写法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder); // 将ViewHolder存储在View中
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
//更优写法
/*@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(resourceId, null);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) convertView.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) convertView.findViewById(R.id.fruit_name);
convertView.setTag(viewHolder); // 将ViewHolder存储在View中
} else {
viewHolder = (ViewHolder) convertView.getTag(); // 重新获取ViewHolder
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return convertView;
}*/
class ViewHolder {
ImageView fruitImage;
TextView fruitName;
}
}
(4)下面修改 MainActivity 中的代码,如下所示:
public class MainActivity extends Activity {
private List<Fruit> fruitList = new ArrayList<Fruit>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits(); // 初始化水果数据
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item, fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
//设置点击事件
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Fruit fruit = fruitList.get(position);
Toast.makeText(MainActivity.this, fruit.getName(),
Toast.LENGTH_SHORT).show();
}
});
}
 
【7】fragment
 
(1)新建一个左侧碎片布局 left_fragment.xml,代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"/>
</LinearLayout>
 
(2)新建右侧碎片布局right_fragment.xml,代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
 
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:text="This is right fragment"
/>
</LinearLayout>
 
(3)LeftFragment
public class LeftFragment extends Fragment {
 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
}
}
inflate()方法的三个参数:
 
  第一个是resource ID,指明了当前的Fragment对应的资源文件;
 
  第二个参数是父容器控件;
 
  第三个布尔值参数表明是否连接该布局和其父容器控件,在这里的情况设置为false,
因为系统已经插入了这个布局到父控件,设置为true将会产生多余的一个View Group。
 
 
除了继承基类 Fragment , 还有一些子类你可能会继承:
    DialogFragment
    显示一个浮动的对话框.  
    用这个类来创建一个对话框,是使用在Activity类的对话框工具方法之外的一个好的选择,
    因为你可以将一个fragment对话框合并到activity管理的fragment back stack中,允许用户返回到一个之前曾被摒弃的fragment.
    ListFragment
    显示一个由一个adapter(例如 SimpleCursorAdapter)管理的项目的列表, 类似于ListActivity.
    它提供一些方法来管理一个list view, 例如 onListItemClick()回调来处理点击事件.
    PreferenceFragment
    显示一个 Preference对象的层次结构的列表, 类似于PreferenceActivity.
    这在为你的应用创建一个"设置"activity时有用处.
 
(4)RightFragment
public class RightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
}
}
 
(5)修改 activity_main.xml中的代码,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
 
【8】动态添加碎片
1. 创建待添加的碎片实例。
2. 获取到 FragmentManager,在活动中可以直接调用 getFragmentManager()方法得到。 FragmentManager fragmentManager = getFragmentManager();
3. 开启一个事务,通过调用 beginTransaction()方法开启。 FragmentTransaction transaction = fragmentManager.beginTransaction();
4. 向容器内加入碎片,一般使用 replace()方法实现,需要传入容器的 id 和待添加的碎片实例。 transaction.replace(R.id.right_layout, fragment);
5. 模拟返回栈 transaction.addToBackStack(null);
6. 提交事务,调用 commit()方法来完成。 transaction.commit();
 
【9】广播
 
(1)动态注册广播
 
intentFilter = new IntentFilter(); 
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "network changes",
Toast.LENGTH_SHORT).show();
}
}
 
(2)静态注册
 
<receiver android:name=".MyBroadcastReceiver">
<intent-filter 
<--优先级设置-->
android:priority="100" >
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
 
【10】将数据存储到文件中
 
Context 类中提供了一个 openFileOutput ()方法,可以用于将数据存储到指定的文件中。
这个方法接收两个参数,第一个参数是文件名(不包含路径),第 二 个 参 数 是 文 件 的 操 作 模 式 , 主 要 有 两 种 模 式 可 选 ,
MODE_PRIVATE 和 MODE_APPEND。其中 MODE_PRIVATE 是默认的操作模式,表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容,
而 MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件。
 
public void save() {
String data = "Data to save";
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
 
【11】从文件中读取数据
 
Context 类中提供了一个 openFileInput()方法,它只接收一个参数,即要读取的文件名
 
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
 
【12】SharedPreferences 存储
1. Context 类中的 getSharedPreferences()方法
2. Activity 类中的 getPreferences()方法
3. PreferenceManager 类中的 getDefaultSharedPreferences()方法
 
使用:
1.获取 SharedPreferences 实例    
2. 调用 SharedPreferences 对象的 edit()方法来获取一个 SharedPreferences.Editor 对象。
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
3. 向 SharedPreferences.Editor 对象中添加数据, 比如添加一个布尔型数就使用putBoolean方法,添加一个字符串则使用 putString()方法,以此类推。
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
4. 调用 commit()方法将添加的数据提交,从而完成数据存储操作。
editor.commit();
 
从 SharedPreferences 中读取数据:
SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
 
【13】数据库
 
(1)创建数据库
使用一个类继承 SQLiteOpenHelper
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table book ("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "pages integer, "
+ "name text)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, CursorFactoryfactory, int version) {
super(context, name, factory, version);
mContext = context;
}
//第一次建库时调用
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
}
//升级数据库时调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
}
}
 
(2)添加数据
 
调用 SQLiteOpenHelper 的 getReadableDatabase()或 getWritableDatabase()返回一个 SQLiteDatabase 对象
1.insert
 
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values); // 插入条数据
values.clear();
 
2. delete
 
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages > ?", new String[] { "500" });
 
3. update
 
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name = ?", new String[] { "The DaVinci Code" });
 
4.query
 
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 查询Book表中所有的数据
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
// 遍历Cursor对象,取出数据并打印
String name = cursor.getString(cursor.getColumnIndex("name"));
String author = cursor.getString(cursor.
getColumnIndex("author"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
} while (cursor.moveToNext());
}
cursor.close();
}
 
(3)使用事务
 
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction(); // 开启事务
try {
db.delete("Book", null, null);
if (true) {
// 在这里手动抛出一个异常,让事务失败
throw new NullPointerException();
}
ContentValues values = new ContentValues();
values.put("name", "Game of Thrones");
values.put("author", "George Martin");
values.put("pages", 720);
values.put("price", 20.85);
db.insert("Book", null, values);
db.setTransactionSuccessful(); // 事务已经执行成功
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction(); // 结束事务
}
 
(4)升级数据库最佳写法
 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL(CREATE_CATEGORY);
case 2:
db.execSQL("alter table Book add column category_id integer");
default:
}
}
 
【14】ContentResolver 的基本用法
 
内容 URI 最标准的格式写法如下:
content://com.example.app.provider/table1
content://com.example.app.provider/table2
Uri uri = Uri.parse("content://com.example.app.provider/table1")
 
(1)更新:
Cursor cursor = getContentResolver().query(uri,//指定查询某个应用程序下的某一张表
projection,//指定查询的列名
selection,//指定 where 的约束条件
selectionArgs,//为 where 中的占位符提供具体的值
sortOrder);//指定查询结果的排序方式
 
if (cursor != null) {
while (cursor.moveToNext()) {
String column1 = cursor.getString(cursor.getColumnIndex("column1"));
int column2 = cursor.getInt(cursor.getColumnIndex("column2"));
}
cursor.close();
}
 
(2)插入
ContentValues values = new ContentValues();
values.put("column1", "text");
values.put("column2", 1);
getContentResolver().insert(uri, values);
 
(3)更新
ContentValues values = new ContentValues();
values.put("column1", "");
getContentResolver().update(uri, values, "column1 = ? and column2 = ?", new
String[] {"text", "1"});
 
(4)删除
getContentResolver().delete(uri, "column2 = ?", new String[] { "1" });
 
【15】ContentProvider
新建一个类去继承 ContentProvider 的方式来创建一个自己的内容提供器。实现 ContentProvider 类中六个抽象方法,
private static UriMatcher uriMatcher;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("com.example.app.provider", "table1", TABLE1_DIR);
uriMatcher.addURI("com.example.app.provider ", "table1/#", TABLE1_ITEM);
uriMatcher.addURI("com.example.app.provider ", "table2", TABLE2_ITEM);
uriMatcher.addURI("com.example.app.provider ", "table2/#", TABLE2_ITEM);
}
 
getType()方法:
1.必须以 vnd 开头。
2.如果内容 URI 以路径结尾,则后接 android.cursor.dir/,如果内容 URI 以 id 结尾,则后接 android.cursor.item/。
3. 最后接上 vnd.<authority>.<path>。
 
【16】使用通知
 
1.不推荐
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker text", System.currentTimeMillis());
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
//被删除
notification.setLatestEventInfo(this, "This is content title","This is content text", pi);
manager.notify(1, notification);
 
2.系统推荐
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, DD.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.sym_def_app_icon)    //图标  要显示notification必须有图标,不然会报错
                .setContentTitle("标题")
                .setContentInfo("右下角")
                .setContentText("内容")
                .setAutoCancel(true)    //点击一下就消失
                .setContentIntent(pendingIntent)   //延迟意图
                .setTicker("刚出来是在手机最上方显示,一会就消失")
                .setWhen(System.currentTimeMillis())    //消息的时间
                .build();   //创建notification
//        notification.flags = Notification.FLAG_AUTO_CANCEL;      跟setAutoCancel一样作用
        //显示notification  第一个参数不能重复,否则就只能显示重复的最后一个notification
        manager.notify(1,notification);
 
    3.自定义notification
    
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.activity_main);
    remoteViews.setImageViewResource(R.id.imageView,android.R.drawable.sym_def_app_icon);
    remoteViews.setTextViewText(R.id.textText,"textview 的内容");
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent intent = new Intent(this, DD.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    Notification notification = new NotificationCompat.Builder(this)
            .setAutoCancel(true)    //点击一下就消失
            .setContentIntent(pendingIntent)   //延迟意图
            .setContent(remoteViews)     //设置自定义的view
            .build();
    manager.notify(1,notification);
【17】调用摄像头拍照
 
// 创建File对象,用于存储拍照后的图片
File outputImage = new File(Environment.getExternalStorageDirectory(), "tempImage.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action. IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
}
 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHOTO); // 启动裁剪程序
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory.decodeStream
(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
 
【18】从相册中选择照片
 
// 创建File对象,用于存储选择的照片
File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
intent.putExtra("crop", true);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHOTO);
}
 
 
【19】播放多媒体文件
(1)音频
MediaPlayer mediaPlayer = new MediaPlayer();
setDataSource()  设置要播放的音频文件的位置。
prepare()  在开始播放之前调用这个方法完成准备工作。
start()  开始或继续播放音频。
pause()  暂停播放音频。
reset()  将 MediaPlayer 对象重置到刚刚创建的状态。
seekTo()  从指定的位置开始播放音频。
stop()  停止播放音频。调用这个方法后的 MediaPlayer 对象无法再播放音频。
release()  释放掉与 MediaPlayer 对象相关的资源。
isPlaying()  判断当前 MediaPlayer 是否正在播放音频。
getDuration()  获取载入的音频文件的时长。
 
(2)视频
videoView = (VideoView) findViewById(R.id.video_view);
setVideoPath()  设置要播放的视频文件的位置。
start()  开始或继续播放视频。
pause()  暂停播放视频。
resume()  将视频重头开始播放。
seekTo()  从指定的位置开始播放视频。
isPlaying()  判断当前是否正在播放视频。
getDuration()  获取载入的视频文件的时长。
 
【20】使用 AsyncTask
 
1.class DownloadTask extends AsyncTask<Void, Integer, Boolean>
2.onPreExecute() 这个方法会在后台任务开始执行之前调用,用于进行一些界面上的初始化操作,比如显示一个进度条对话框等。
3. doInBackground(Params...)这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任务。
如果需要更新 UI 元素,可以调用 publishProgress(Progress...)方法来完成。
4. onProgressUpdate(Progress...)当在后台任务中调用了 publishProgress(Progress...)方法后,
这个方法就会很快被调用,方法中携带的参数就是在后台任务中传递过来的。
5. onPostExecute(Result)当后台任务执行完毕并通过 return 语句进行返回时,这个方法就很快会被调用。
返回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些 UI 操作.
6.如果想要启动这个任务,只需编写以下代码即可:new DownloadTask().execute();
 
【21】活动与服务联系
 
MainActivity中
 
onServiceConnected()方法和 onServiceDisconnected()方法,这两个方法分别会在活动与服务成功绑定以及解除绑定的时候调用
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
 
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务
 
Service 
 
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
public void startDownload() {
Log.d("MyService", "startDownload executed");
}
public int getProgress() {
Log.d("MyService", "getProgress executed");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
 
【22】使用 IntentService,直接在服务里去处理一些耗时的逻辑,防止出现 ANR。
 
public class MyIntentService extends IntentService {
 
public MyIntentService() {
super("MyIntentService"); // 调用父类的有参构造函数
}
@Override
protected void onHandleIntent(Intent intent) {
// 打印当前线程的id
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}
}
 
【23】Alarm 机 制 的 用 法,它具有唤醒 CPU 的功能,即可以保证每次需要执行定时任务的时候 CPU 都能正常工作。
 
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int anHour = 60 * 60 * 1000; // 这是一小时的毫秒数
long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
Intent i = new Intent(this, AlarmReceiver.class /*跳转到某一个具体的类*/);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
 
【24】WebView 的用法
 
webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true); //让 WebView 支持 JavaScript 脚本
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url); // 根据传入的参数再去加载新的网页
return true; // 表示当前WebView可以处理打开新网页的请求,不用借助
系统浏览器
}
});
webView.loadUrl("http://www.baidu.com");
 
【25】使用 HttpURLConnection
 
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
  1.URL url = new URL("http://www.baidu.com");
  2.connection = (HttpURLConnection) url.openConnection();
  3.connection.setRequestMethod("GET");
  4.connection.setConnectTimeout(8000);
  5.connection.setReadTimeout(8000);
  6.InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(newInputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
}
}
 
【26】使用 HttpClient
 
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 请求和响应都成功了
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
}
}
}
 
【27】解析 XML 格式数据
 
(1)Pull 解析方式
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventType) {
// 开始解析某个结点
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
id = xmlPullParser.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPullParser.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPullParser.nextText();
}
break;
}
// 完成解析某个结点
case XmlPullParser.END_TAG: {
if ("app".equals(nodeName)) {
Log.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
 
(2)SAX 解析方式
 
新建一个类继承自 DefaultHandler 类,复写方法。
 
  public void startDocument() throws SAXException {
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
// 记录当前结点名
nodeName = localName;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// 根据当前的结点名判断将内容添加到哪一个StringBuilder对象中
if ("id".equals(nodeName)) {
id.append(ch, start, length);
} else if ("name".equals(nodeName)) {
name.append(ch, start, length);
} else if ("version".equals(nodeName)) {
version.append(ch, start, length);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws
SAXException {
if ("app".equals(localName)) {
Log.d("ContentHandler", "id is " + id.toString().trim());
Log.d("ContentHandler", "name is " + name.toString().trim());
Log.d("ContentHandler", "version is " + version.toString().trim());
// 最后要将StringBuilder清空掉
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void endDocument() throws SAXException {
 
}
 
【28】解析 JSON 格式数据
 
(1)使用 JSONObject
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
}
}
 
(2)使用 GSON
 
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
for (App app : appList) {
Log.d("MainActivity", "id is " + app.getId());
Log.d("MainActivity", "name is " + app.getName());
Log.d("MainActivity", "version is " + app.getVersion());
}
 
【29】LocationManager 的基本用法
 
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 获取所有可用的位置提供器
List<String> providerList = locationManager.getProviders(true);
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
// 当没有可用的位置提供器时,弹出Toast提示用户
Toast.makeText(this, "No location provider to use",
Toast.LENGTH_SHORT).show();
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// 显示当前设备的位置信息
showLocation(location);
}
locationManager.requestLocationUpdates(provider, 5000, 1,locationListener);
}
protected void onDestroy() {
super.onDestroy();
if (locationManager != null) {
// 关闭程序时将监听器移除
locationManager.removeUpdates(locationListener);
}
}
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundleextras) {
 
}
@Override
public void onProviderEnabled(String provider) {
 
}
@Override
public void onProviderDisabled(String provider) {
 
}
@Override
public void onLocationChanged(Location location) {
// 更新当前设备的位置信息
showLocation(location);
}
};
 
【30】使用传感器
 
(1)光照传感器
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(listener);
}
}
private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// values数组中第一个下标的值就是当前的光照强度
float value = event.values[0];
lightLevel.setText("Current light level is " + value + " lx");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
}
};
 
(2)加速度传感器
 
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(listener);
}
}
private SensorEventListener listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// 加速度可能会是负值,所以要取它们的绝对值
float xValue = Math.abs(event.values[0]);
float yValue = Math.abs(event.values[1]);
float zValue = Math.abs(event.values[2]);
if (xValue > 15 || yValue > 15 || zValue > 15) {
// 认为用户摇动了手机,触发摇一摇逻辑
Toast.makeText(MainActivity.this, "摇一摇",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
}
};
 
(3)方向传感器
 
分别获取到加速度传感器和地磁传感器的实例,并给它们注册监听器 。
 
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);//地磁传感器
Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//加速度传感器
sensorManager.registerListener(listener, magneticSensor,SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(listener, accelerometerSensor,SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(listener);
}
}
private SensorEventListener listener = new SensorEventListener() {
float[] accelerometerValues = new float[3];
float[] magneticValues = new float[3];
@Override
public void onSensorChanged(SensorEvent event) {
// 判断当前是加速度传感器还是地磁传感器
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// 注意赋值时要调用clone()方法
accelerometerValues = event.values.clone();
} else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// 注意赋值时要调用clone()方法
magneticValues = event.values.clone();
}
float[] R = new float[9];
float[] values = new float[3];
SensorManager.getRotationMatrix(R, null, accelerometerValues,magneticValues);
SensorManager.getOrientation(R, values);
Log.d("MainActivity", "value[0] is " + Math.toDegrees(values[0]));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
}
};
 
【31】使用 Intent 传递对象,使用序列化
 
(1)Serializable 方式
 
让一个类去实现 Serializable 这个接口 。
 
接下来在 FirstActivity 中的写法非常简单:
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
 
接下来在 SecondActivity 中获取这个对象也很简单,写法如下:
Person person = (Person) getIntent().getSerializableExtra("person_data");
 
(2)Parcelable 方式
 
public class Person implements Parcelable {
private String name;
private int age;
......
@Override
public int describeContents() {
return 0;
} 0
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name); // 写出name
dest.writeInt(age); // 写出age
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.name = source.readString(); // 读取name
person.age = source.readInt(); // 读取age
return person;
}
@Override
public Person[] newArray(int size) {
                                                                                                                                                      return new Person[size];
}
};
}
 
SecondActivity 中获取对象的时候,如下所示:
Person person = (Person) getIntent().getParcelableExtra("person_data");
 
32.
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_photo_gallery_image_view"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:scaleType="centerCrop">
<!--android:scaleType="centerCrop"   作用:先居中放置图片,然后放大较小图片,裁剪较大图片(裁剪时裁剪图片两头)以匹配视图-->
</ImageView>
 
33.RunOnUIThread
在子线程里更新UI的简单方法
        new Thread(){
            @Override
            public void run() {
                super.run();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(),"www",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
 
 
34.viewPager
 
1)ViewPager类继承了ViewGroup类,可以在其中添加其他的view。
 
2)ViewPager类需要PagerAdapter适配器类提供数据。
 
使用viewpager时一般需要使用PagerTitleStrip类和PagerTabStrip 类,PagerTitleStrip类继承自ViewGroup类,而PagerTabStrip类继承PagerTitleStrip类,
 
这两 个类是容器类。注意,在定义XML的layout的时候,这两个类必须是ViewPager的子标签,不然会出错。
 
布局文件xml:
 
 
 
<RelativeLayout 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" >
 
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
 
        <android.support.v4.view.PagerTabStrip
            android:id="@+id/tabstrip"
            android:layout_width="wrap_content"
            android:layout_height="30dip"
            android:gravity="center" />
    </android.support.v4.view.ViewPager>
 
</RelativeLayout>
 
 
 
 MainActivity.class:
 
 
 
public class MainActivity extends AppCompatActivity {
 
private ViewPager pager;
private PagerTabStrip tabStrip ;
private List<View> viewContainter = new ArrayList<View>();
private List<String> titleContainer = new ArrayList<String>();
private static String TAG = "MainActivity";
 
@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
 
 
pager = (ViewPager)findViewById(R.id.viewpager);
tabStrip = (PagerTabStrip)findViewById(R.id.tabstrip);
//取消tab下面的长横线
tabStrip.setDrawFullUnderline(false);
//设置tabStrip的背景色
tabStrip.setBackgroundColor(this.getResources().getColor(R.color.bg));
//设置当前tabStrip页签的下划线颜色
tabStrip.setTabIndicatorColor(this.getResources().getColor(R.color.bule));
tabStrip.setTextSpacing(200);
 
View view1 = LayoutInflater.from(this).inflate(R.layout.tab_item1, null);
View view2 = LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
View view3 = LayoutInflater.from(this).inflate(R.layout.tab_item3, null);
View view4 = LayoutInflater.from(this).inflate(R.layout.tab_item4, null);
 
            //viewpager开始添加view
viewContainter.add(view1);
viewContainter.add(view2);
viewContainter.add(view3);
viewContainter.add(view4);
 
            //页签项
titleContainer.add("title1");
titleContainer.add("title2");
titleContainer.add("title3");
titleContainer.add("title4");
 
         //设置ViewPager控件的适配器
pager.setAdapter(new PagerAdapter() {
 
//viewpager中的组件数量
@Override
public int getCount() {
return viewContainter.size();
}
 
              @Override 
              public boolean isViewFromObject(View arg0, Object arg1) {   
                  return arg0 == arg1; 
              }
 
                  //销毁position位置的界面
@Override
public void destroyItem(ViewGroup container, int position,
Object object) {
((ViewPager) container).removeView(viewContainter.get(position));
}
                  //初始化position位置的界面,每次滑动的时候生成的组件
@Override
public Object instantiateItem(ViewGroup container, int position) {
((ViewPager) container).addView(viewContainter.get(position));
return viewContainter.get(position);
}
 
@Override
public CharSequence getPageTitle(int position) {
return titleContainer.get(position);
}
              
              @Override 
              public int getItemPosition(Object object) { 
                  return super.getItemPosition(object); 
              }
 
});
 
pager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int arg0) {
Log.d(TAG, arg0);
}
 
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.d(TAG, "arg0:" + arg0);
Log.d(TAG, "arg1:" + arg1);
Log.d(TAG, "arg2:" + arg2);
}
 
@Override
public void onPageSelected(int arg0) {
Log.d(TAG, arg0);
}
});
 
}
 
}
 
 注意:
 
使用PageAdapter至少要实现下面的4个方法:
 
public Object instantiateItem(ViewGroup container, int position)
 
public void destroyItem(ViewGroup container, int position,Object object) 
 
public int getCount()
 
public boolean isViewFromObject(View arg0, Object arg1) 
 
 
 

Android基础知识大全(精品)的更多相关文章

  1. 【Xamarin开发 Android 系列 4】 Android 基础知识

    原文:[Xamarin开发 Android 系列 4] Android 基础知识 什么是Android? Android一词的本义指“机器人”,同时也是Google于2007年11月5日宣布的基于Li ...

  2. Android基础知识巩固:关于PendingIntent和广播

    平时使用广播的场合比较多,但细节的东西,看过了也没有总结,以至于某些场合有小问题,还是要把原理和属性搞清楚才能运用自如. 其实也是自己比较懒,先看别人的blog,有个概念再去官网看英文的能好理解一些. ...

  3. Android基础知识(一)

    前言 前言 从软件测试最终目的发现问题缺陷来看,Findyou比较认同一个观念,测试的能力大致可以划分成三个能力层次:发现问题.定位问题.预防问题.有机会探讨一下这个分类. 发现问题各种方式方法,比如 ...

  4. android开发学习---linux下开发环境的搭建&& android基础知识介绍

    一.配置所需开发环境 1.基本环境配置 JDK 5或以上版本(仅有JRE不够) (http://www.oracle.com/technetwork/java/javase/downloads/ind ...

  5. mysql基础知识大全

    前言:本文主要为mysql基础知识的大总结,mysql的基础知识很多,这里作简单概括性的介绍,具体的细节还是需要自行搜索.当然本文还有很多遗漏的地方,后续会慢慢补充完善. 数据库和数据库软件 数据库是 ...

  6. 【值得收藏】C语言入门基础知识大全!从C语言程序结构到删库跑路!

    01 C语言程序的结构认识 用一个简单的c程序例子,介绍c语言的基本构成.格式.以及良好的书写风格,使小伙伴对c语言有个初步认识. 例1:计算两个整数之和的c程序: #include main() { ...

  7. Android基础知识-1

    1.Android的Activity任务栈 在Android的系统中,在APP运行时每个APP都会默认有一个任务栈,任务栈的名称以APP的包名命名.任务栈是一中先进后出的结构,APP中每一个调用的Ac ...

  8. 看看android基础知识,谁帮我作答

    无论怎么着,了解一点android的基本知识还是有必要的,就当开阔一些自己的眼界吧. .. . android的四大功能组件是_activity_,_service_,_BroadcastReceiv ...

  9. Android基础知识学习

    IPC  (Inter-Process Communication) 意思是: 进程间的通信,是指两个进程之间进行数据交换的过程. Android中如何开启多进程呢? 只需要给四大组件(Activit ...

随机推荐

  1. 蓝桥杯比赛javaB组练习《生日蜡烛》

    题目如下: 生日蜡烛 某君从某年开始每年都举办一次生日party,并且每次都要吹熄与年龄相同根数的蜡烛. 现在算起来,他一共吹熄了236根蜡烛. 请问,他从多少岁开始过生日party的? 请填写他开始 ...

  2. year:2017 month:07 day:31

    2017-07-31 JAVA se 1:基础 控制语句:continue语句:退出本次循环 break语句:退出当前循环 循环语句:for(初始化:条件表达式:循环体){循环语句} 先初始化,再执行 ...

  3. unable to create …

    问题描述: 在新建Android Application时会出现unable to create the selected property page 解决方法: 将用户PATH路径中的jdk路径放到 ...

  4. 1.初入GitHub

    进入github官网,点击右上角注册按钮.  填写账号名,邮箱和密码    选择免费的公开仓库,点击完成就提示注册成功了.   ps:付费一般是给企业用户使用的,用来存放一些不公开的代码.所以是付费的 ...

  5. JAVA WEB主流开发工具下载集

    JAVA SEhttp://www.oracle.com/technetwor ... ownloads/index.html eclipsehttp://www.eclipse.org/downlo ...

  6. JUnit4在Eclipse中的使用

    测试是项目开发中很重要的一环.实际上,建议的项目前期编写过程是:构思-> 编写单元测试代码-> 编写接口->编写实现类-> 测试实现类->编写主类....JUnit是一个 ...

  7. LINUX环境并发服务器的三种实现模型

    服务器设计技术有很多,按使用的协议来分有TCP服务器和UDP服务器.按处理方式来分有循环服务器和并发服务器. 1  循环服务器与并发服务器模型 在网络程序里面,一般来说都是许多客户对应一个服务器,为了 ...

  8. 【leetcode】349. Intersection of Two Arrays

    Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1 ...

  9. 基于FPGA的RGB565_YCbCr_Gray算法实现

    前面我们讲了基于FPGA用VGA显示一副静态图片,那么接下来我们就接着前面的工程来实现我们图像处理的基础算法里最简单的一个那就是彩色图像转灰度的实现. 将彩色图像转化为灰度的方法有两种,一个是令RGB ...

  10. 第2天:HTML常用标签

    今天学完主要对所学知识点进行了整理. 一.超链接ahref:www.baidu.com(跳转页面):id名(锚点跳到相应div位置):01.rar(压缩包) target:_blank(新窗口打开): ...