Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓小案例收集五(內容提供者、動畫)

安卓小案例收集五(內容提供者、動畫)

日期:2017/2/23 15:22:16      編輯:關於Android編程

內容提供者

配置:

Provider:

public class PersonProvider extends ContentProvider {
    private SQLiteDatabase db;
    //創建uri匹配器
    UriMatcher um = new UriMatcher(UriMatcher.NO_MATCH);
    {
        //添加匹配規則
        //arg0:主機名
        //arg1:路徑
        //arg2:匹配碼
        um.addURI("com.itheima.people", "person", 1);//content://com.itheima.people/person
        um.addURI("com.itheima.people", "handsome", 2);//content://com.itheima.people/handsome
        um.addURI("com.itheima.people", "person/#", 3);//content://com.itheima.people/person/10
    }

    //內容提供者創建時調用
    @Override
    public boolean onCreate() {
        MyOpenHelper oh = new MyOpenHelper(getContext());
        db = oh.getWritableDatabase();
        return false;
    }

    //values:其他應用要插的數據
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if(um.match(uri) == 1){
            db.insert("person", null, values);

            //數據庫改變了,內容提供者發出通知
            //arg0:通知發到哪個uri上,注冊在這個uri上的內容觀察者都可以收到通知
            getContext().getContentResolver().notifyChange(uri, null);
        }
        else if(um.match(uri) == 2){
            db.insert("handsome", null, values);

            getContext().getContentResolver().notifyChange(uri, null);
        }
        else{
            throw new IllegalArgumentException("uri傳錯啦傻逼");
        }
        return uri;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int i = 0;
        if(um.match(uri) == 1){
            i = db.delete("person", selection, selectionArgs);
        }
        else if(um.match(uri) == 2){
            i = db.delete("handsome", selection, selectionArgs);
        }
        else{
            throw new IllegalArgumentException("uri又傳錯啦傻逼");
        }

        return i;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int i = db.update("person", values, selection, selectionArgs);
        return i;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        if(um.match(uri) == 1){
            cursor = db.query("person", projection, selection, selectionArgs, null, null, sortOrder, null);
        }
        else if(um.match(uri) == 2){
            cursor = db.query("handsome", projection, selection, selectionArgs, null, null, sortOrder, null);
        }
        else if(um.match(uri) == 3){
            //取出uri末尾攜帶的數字
            long id = ContentUris.parseId(uri);
            cursor = db.query("person", projection, "_id = ?", new String[]{"" + id}, null, null, sortOrder, null);
        }
        return cursor;
    }

    //返回通過指定uri獲取的數據的mimetype
    @Override
    public String getType(Uri uri) {
        if(um.match(uri) == 1){
            return "vnd.android.cursor.dir/person";
        }
        else if(um.match(uri) == 2){
            return "vnd.android.cursor.dir/handsome";
        }
        else if(um.match(uri) == 3){
            return "vnd.android.cursor.item/person";
        }
        return null;
    }
}

OpenHelper:

public class MyOpenHelper extends SQLiteOpenHelper {
    public MyOpenHelper(Context context) {
        super(context, "people.db", null, 2);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), money integer(10))");

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("create table handsome(_id integer primary key autoincrement, name char(10), phone char(20))");
    }
}

調用:

public void insert(View v){
    //通過內容提供者把數據插入01數據庫
    //1.獲取contentResolver
    ContentResolver resolver = getContentResolver();
    //2.訪問內容提供者,插入數據
    ContentValues values = new ContentValues();
    values.put("name", "流氓潤");
    values.put("phone", 138992);
    values.put("money", 14000);
    //arg0:指定內容提供者的主機名
    resolver.insert(Uri.parse("content://com.itheima.people/person"), values);

    values.clear();
    values.put("name", "侃哥");
    values.put("phone", 15999);
    //arg0:指定內容提供者的主機名
    resolver.insert(Uri.parse("content://com.itheima.people/handsome"), values);
   }

   public void delete(View v){
    ContentResolver resolver = getContentResolver();
    int i = resolver.delete(Uri.parse("content://com.itheima.people"), "name = ?", new String[]{"鳳姐"});
    System.out.println(i);
   }

   public void update(View v){
    ContentResolver resolver = getContentResolver();
    ContentValues values = new ContentValues();
    values.put("money", 16001);
    int i = resolver.update(Uri.parse("content://com.itheima.people"), values, "name = ?", new String[]{"春曉"});
    System.out.println(i);
   }

   public void query(View v){
    ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://com.itheima.people/person"), null, null, null, null);
    while(cursor.moveToNext()){
        String name = cursor.getString(1);
        String phone = cursor.getString(2);
        String money = cursor.getString(3);
        System.out.println(name + ";" + phone + ";" + money);
    }
   }
   public void queryOne(View v){
    ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://com.itheima.people/person/4"), null, null, null, null);
    if(cursor.moveToNext()){
        String name = cursor.getString(1);
        String phone = cursor.getString(2);
        String money = cursor.getString(3);
        System.out.println(name + ";" + phone + ";" + money);
    }
   }

獲取系統短息

   public void click1(View v){
    ContentResolver resolver = getContentResolver();
    Cursor cursor = resolver.query(Uri.parse("content://sms"), new String[]{"address", "date", "type", "body"}, null, null, null);
    while(cursor.moveToNext()){
        String address = cursor.getString(0);
        long date = cursor.getLong(1);
        int type = cursor.getInt(2);
        String body = cursor.getString(3);

        System.out.println(address + ";" + date + ";" + type + ";" + body);
    }
   }

插入系統短信

public void click(View v){
    Thread t = new Thread(){
        @Override
        public void run() {
            try {
                sleep(7000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ContentResolver resolver = getContentResolver();
            ContentValues values = new ContentValues();
            values.put("address", 95555);
            values.put("date", System.currentTimeMillis());
            values.put("type", 1);
            values.put("body", "您尾號為XXXX的招行儲蓄卡收到轉賬1,000,000");
            resolver.insert(Uri.parse("content://sms"), values);
        }
    };
    t.start();

   }

獲取系統聯系人

public void click(View v){
    ContentResolver resolver = getContentResolver();

    Cursor cursor = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts"), new String[]{"contact_id"}, 
            null, null, null);
    while(cursor.moveToNext()){
        String contactId = cursor.getString(0);
        //使用聯系人id作為where條件去查詢data表,查詢出屬於該聯系人的信息
        Cursor cursorData = resolver.query(Uri.parse("content://com.android.contacts/data"), new String[]{"data1", "mimetype"}, "raw_contact_id = ?", 
                new String[]{contactId}, null);
//          Cursor cursorData = resolver.query(Uri.parse("content://com.android.contacts/data"), null, "raw_contact_id = ?", 
//                  new String[]{contactId}, null);

//          int count = cursorData.getColumnCount();
//          for (int i = 0; i < count; i++) {
//              System.out.println(cursorData.getColumnName(i));
//          }

        Contact contact = new Contact();
        while(cursorData.moveToNext()){
            String data1 = cursorData.getString(0);
            String mimetype = cursorData.getString(1);
//              System.out.println(data1 + ";" + mimetype);
            if("vnd.android.cursor.item/email_v2".equals(mimetype)){
                contact.setEmail(data1);
            }
            else if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
                contact.setPhone(data1);
            }
            else if("vnd.android.cursor.item/name".equals(mimetype)){
                contact.setName(data1);
            }
        }
        System.out.println(contact.toString());
    }
 }

插入聯系人

public void click(View v){
    ContentResolver resolver = getContentResolver();
    //先查詢最新的聯系人的主鍵,主鍵+1,就是要插入的聯系人id
    Cursor cursor = resolver.query(Uri.parse("content://com.android.contacts/raw_contacts"), new String[]{"_id"}, null, null, null);
    int _id = 0;
    if(cursor.moveToLast()){
        _id = cursor.getInt(0);
    }
    _id++;

    //插入聯系人id
    ContentValues values = new ContentValues();
    values.put("contact_id", _id);
    resolver.insert(Uri.parse("content://com.android.contacts/raw_contacts"), values);

    //把具體聯系人信息插入data表
    values.clear();
    values.put("data1", "剪刀手坤哥");
    values.put("mimetype", "vnd.android.cursor.item/name");
    values.put("raw_contact_id", _id);
    resolver.insert(Uri.parse("content://com.android.contacts/data"), values);

    values.clear();
    values.put("data1", "8899667");
    values.put("mimetype", "vnd.android.cursor.item/phone_v2");
    values.put("raw_contact_id", _id);
    resolver.insert(Uri.parse("content://com.android.contacts/data"), values);
   }

內容觀察者

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //注冊內容觀察者,觀察者就生效了,可以接受內容提供者發出的通知
    ContentResolver resolver = getContentResolver();
    //arg0:指定接收哪個內容提供者發出的通知
    resolver.registerContentObserver(Uri.parse("content://sms"), 
            true, //如果為true,以這個uri作為開頭的uri上的數據改變了,該內容觀察者都會收到通知
            new MyObserver(new Handler()));
   }

class MyObserver extends ContentObserver{

public MyObserver(Handler handler) {
    super(handler);
    // TODO Auto-generated constructor stub
}

@Override
public void onChange(boolean selfChange) {
    // TODO Auto-generated method stub
    super.onChange(selfChange);
    System.out.println("短信數據庫改變");
    }
}

Fragment

protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       showfagment01();
   }

   private void showfagment01() {
    //1.創建fragment對象
    Fragment01 fragment1 = new Fragment01();
    //2.獲取fragment管理器
    FragmentManager fm = getFragmentManager();
    //3.開啟事務
    FragmentTransaction ft = fm.beginTransaction();
    //4.顯示fragment
    //arg0:設置把fragment顯示在哪個容器中
    ft.replace(R.id.fl, fragment1);
    //5.提交
    ft.commit();
}

   public void click1(View v){
    showfagment01();
   }
   public void click2(View v){
    //1.創建fragment對象
    Fragment02 fragment2 = new Fragment02();
    //2.獲取fragment管理器
    FragmentManager fm = getFragmentManager();
    //3.開啟事務
    FragmentTransaction ft = fm.beginTransaction();
    //4.顯示fragment
    //arg0:設置把fragment顯示在哪個容器中
    ft.replace(R.id.fl, fragment2);
    //5.提交
    ft.commit();
   }
   public void click3(View v){
    //1.創建fragment對象
    Fragment03 fragment3 = new Fragment03();
    //2.獲取fragment管理器
    FragmentManager fm = getFragmentManager();
    //3.開啟事務
    FragmentTransaction ft = fm.beginTransaction();
    //4.顯示fragment
    //arg0:設置把fragment顯示在哪個容器中
    ft.replace(R.id.fl, fragment3);
    //5.提交
            ft.commit();
  }

Fragment數據傳遞

public void click4(View v){
    EditText et_main = (EditText) findViewById(R.id.et_main);
    String text = et_main.getText().toString();
    fragment1.setText(text);
   }

   public void setText(String text){
    TextView tv_main = (TextView) findViewById(R.id.tv_main);
    tv_main.setText(text);
  }

幀動畫

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     ImageView rocketImage = (ImageView) findViewById(R.id.iv);
     //設置iv的背景圖
     rocketImage.setBackgroundResource(R.drawable.plusstolensee);
     //獲取iv的背景
     AnimationDrawable rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
     //開始播放
     rocketAnimation.start();
}

補間動畫

private ImageView iv;
private TranslateAnimation ta;
private ScaleAnimation sa;
private AlphaAnimation aa;
private RotateAnimation ra;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    iv = (ImageView) findViewById(R.id.iv);
}

public void translate(View v){
    //定義位移補間動畫
//      TranslateAnimation ta = new TranslateAnimation(-100, 100, -60, 60);

    ta = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.5f, Animation.RELATIVE_TO_SELF, 1.5f, 
            Animation.RELATIVE_TO_SELF, -2, Animation.RELATIVE_TO_SELF, 2);
    //定義動畫持續時間
    ta.setDuration(2000);
    //設置重復次數
    ta.setRepeatCount(1);
    //設置重復模式
    ta.setRepeatMode(Animation.REVERSE);
    //在結束位置上填充動畫
    ta.setFillAfter(true);
    //播放動畫
    iv.startAnimation(ta);

}

public void scale(View v){
//      ScaleAnimation sa = new ScaleAnimation(0.2f, 2, 0.2f, 2);
//      ScaleAnimation sa = new ScaleAnimation(0.2f, 2, 0.2f, 2, iv.getWidth()/2, iv.getHeight()/2);

    sa = new ScaleAnimation(0.3f, 2, 0.2f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    //定義動畫持續時間
    sa.setDuration(2000);
    //設置重復次數
    sa.setRepeatCount(1);
    //設置重復模式
    sa.setRepeatMode(Animation.REVERSE);
    //在結束位置上填充動畫
    sa.setFillAfter(true);
    //播放動畫
    iv.startAnimation(sa);
}

public void alpha(View v){
    aa = new AlphaAnimation(1, 0.2f);
    aa.setDuration(2000);
    aa.setRepeatCount(1);
    aa.setRepeatMode(Animation.REVERSE);
    aa.setFillAfter(true);
    iv.startAnimation(aa);
}

public void rotate(View v){
//      RotateAnimation ra = new RotateAnimation(0, 720);
//      RotateAnimation ra = new RotateAnimation(0, 720, iv.getWidth()/2, iv.getHeight()/2);

    ra = new RotateAnimation(0, -720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

    ra.setDuration(2000);
    ra.setRepeatCount(1);
    ra.setRepeatMode(Animation.REVERSE);
    ra.setFillAfter(true);
    iv.startAnimation(ra);
}

public void fly(View v){
    //創建動畫集合
    AnimationSet set = new AnimationSet(false);
    //把動畫添加至集合
    set.addAnimation(ta);
    set.addAnimation(sa);
    set.addAnimation(aa);
    set.addAnimation(ra);

    //開始播放集合
    iv.startAnimation(set);
}

屬性動畫

private ImageView iv;
private ObjectAnimator oa1;
private ObjectAnimator oa2;
private ObjectAnimator oa3;
private ObjectAnimator oa4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    iv = (ImageView) findViewById(R.id.iv);
    iv.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "點我上miss", 0).show();
        }
    });
}

public void translate(View v){
//      TranslateAnimation ta = new TranslateAnimation(-100, 100, 0, 0);
//      ta.setDuration(2000);
//      ta.setFillAfter(true);
//      iv.startAnimation(ta);
    //創建屬性動畫師
    //arg0:要操作的對象
    //arg1:要修改的屬性的名字

    oa1 = ObjectAnimator.ofFloat(iv, "translationX", 0, 70, 30, 100);
    oa1.setDuration(2000);
    oa1.setRepeatCount(1);
    oa1.setRepeatMode(ValueAnimator.REVERSE);
    oa1.start();
}

public void scale(View v){
    oa2 = ObjectAnimator.ofFloat(iv, "scaleX", 0.2f, 2, 1, 2.5f);
    oa2.setDuration(2000);
    oa2.setRepeatCount(1);
    oa2.setRepeatMode(ValueAnimator.REVERSE);
    oa2.start();
}

public void alpha(View v){
    oa3 = ObjectAnimator.ofFloat(iv, "alpha", 0.2f, 1);
    oa3.setDuration(2000);
    oa3.setRepeatCount(1);
    oa3.setRepeatMode(ValueAnimator.REVERSE);
    oa3.start();
}

public void rotate(View v){
    oa4 = ObjectAnimator.ofFloat(iv, "rotation", 0, 360, 180, 720);
    oa4.setDuration(2000);
    oa4.setRepeatCount(1);
    oa4.setRepeatMode(ValueAnimator.REVERSE);
    oa4.start();
}

public void fly(View v){
    //創建動畫師集合
    AnimatorSet set = new AnimatorSet();
    //排隊飛
//      set.playSequentially(oa1, oa2, oa3, oa4);
    //一起飛
    set.playTogether(oa1, oa2, oa3, oa4);
    //設置屬性動畫師操作的對象
    set.setTarget(iv);
    set.start();
}

public void xml(View v){
    //使用動畫師填充器把xml資源文件填充成屬性動畫對象
    Animator animator = AnimatorInflater.loadAnimator(this, R.animator.property_animation);
    animator.setTarget(iv);
    animator.start();
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved