安卓小案例收集五(内容提供者、动画)

  • 内容提供者

    • 获取系统短息
    • 插入系统短信
    • 获取系统联系人
    • 插入联系人
    • 内容观察者
    • Fragment
    • Fragment数据传递
    • 帧动画
    • 补间动画
    • 属性动画

内容提供者

配置:

<provider
    android:name="com.itheima.mycontentprovider.PersonProvider"
    android:authorities="com.itheima.people"
    android:exported="true">

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();
}
时间: 2024-08-08 14:17:44

安卓小案例收集五(内容提供者、动画)的相关文章

安卓小案例收集三

收集三 对话框 多线程下载断点续传 XUtils的使用 Activity跳转 Intent跳转并携带数据IntentBundle携带 Activity销毁时传递数据 Receiver案例 ip拨号器示例 短信拦截 SD卡状态监听 流氓软件 应用的安装卸载监听 发送无序广播 优先级及最终接受者 服务 启动停止 电话录音服务 服务的两种启动方式 中间人服务 音乐播放 通过服务手动启动广播接受者 收集三 对话框 public void click1(View v){ //创建对话框创建器 AlertD

安卓小案例收集二

收集二 SQLite数据库 ListView使用 ArrayAdapter和SimpleAdapter的使用 网络请求下载图片 子线程刷新页面Handler的使用网络请求必须在子线程 带缓存的图片下载 使用SmartImageView 工具包loopj 请求html页面并显示其代码 模拟一个新闻客户端 get方式提交表单 post方式提交 使用HttpClient提交表单 异步HttpClient 收集二 SQLite数据库 OpenHelper类: public class MyOpenHel

安卓小案例收集四(多媒体)

加载大图片 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View v){ Options opts = new Options(); //只请求图片宽高,不解析图片像素 opts.inJustDecodeBounds = tr

【安卓】如何使用广播和内容提供者来叫醒小伙伴(控制你的朋友)

摘要:通过多种方法来获取最新短信(静态广播,动态广播,监测数据库变动),保证短信的稳定获取,为了保证应用正常运行,代码中使用开机启动 service的方法,并且能够保证程序不被用户意外关闭出现无法提醒的问题,收到命令后使用内容提供者删除命令短信 ============================================================================================================================= 正

8天入门docker系列 —— 第五天 使用aspnetcore小案例熟悉容器互联和docker-compose一键部署

原文:8天入门docker系列 -- 第五天 使用aspnetcore小案例熟悉容器互联和docker-compose一键部署 这一篇继续完善webnotebook,如果你读过上一篇的内容,你应该知道怎么去挂载webnotebook日志和容器的远程访问,但是这些还远不够,webnotebook 总要和一些数据库打交道吧,比如说mysql,mongodb,redis,通常情况下这些存储设备要么是以容器的方式承载,要么是由DBA在非容器环境下统一管理. 一:webnotebook连接容器redis

[安卓应用开发] 06.内容提供者

*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: poin

微信小程序入门五: wxml文件引用、模版、生命周期

实例内容 wxml文件引用(include.import) 模版 小程序生命周期 实例一: include方式引用header.wxml文件 文件引用对于代码的重用非常重要,例如在web开发中我们可以将公用的header部分和footer等部分进行提取,然后在需要的地方进行引用. 微信小程序里面,是包含引用功能的--include.import.这两个引用文件的标签,使用基本差不多,这里先说一下include. 微信中的视图文件引用,引用过来的都是没有渲染的,基本类似于直接将引用过来的文件复制到

android 53 ContentProvider内容提供者

ContentProvider内容提供者:像是一个中间件一样,一个媒介一样,可以以标准的增删改差操作对手机的文件.数据库进行增删改差.通过ContentProvider查找sd卡的音频文件,可以提供标准的方法而且不用知道音频文件在那个文件夹里面,只要设置条件就可以找到. 安卓系统把音视频.图片存在系统内部的数据库里面,ContentProvider操作的是数据库不是去文件夹里面去找.sd卡和内存卡的文件安卓系统都会登记,登记文件类型.路径,文件名,文件大小都保存在数据库里.ContentProv

android闹钟小案例之知识点总结

上一篇文章对近期做的小闹钟做了功能阐述,现在来总结下整个开发过程中所用到的一些知识点: 1.TimePicker的监听 TimePicker控件是整个应用的核心,其它的操作都得基于对该控件的正确操控.对该控件的操作重要就是为其设置监听器,在监听事件中获取用户设置的时间. private Calendar calendar=Calendar.getInstance();//创建calendar对象 private class OnTimeChangedListenerImpl implements