ContentObserver的小demo 注册和取消注册

本文提供了一个ContentObserver的简单示例,重点介绍了如何在onCreate和onResume中进行注册,以及在onDestroy和onPause中进行取消注册的操作。
摘要由CSDN通过智能技术生成

主要的代码是注册和取消注册

 

注册需要在onCreate 或者是onResume里面

而反注册要和上面的对应了, 就是onDestory 或者是onPause里面

 

package bjpkten.aclient;

import android.Manifest;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Handler mHandler = new Handler();
    private String TAG = "kodulf";
    private String[] permissions = {Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS,Manifest.permission.READ_CALENDAR};
    private AlertDialog dialog;
    private int currentPosition = -1;
    private ContentObserver mContentObserver = new ContentObserver(mHandler) {
        @Override
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            Log.d(TAG, "onChange: ");
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);

            Log.d(TAG, "onChange: uri " + uri.getAuthority());
        }
    };

    private ServiceConnection conn;
    private Fighting fighting;

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

        Intent intent = new Intent();
        intent.setAction("aa.bb.cc.dd");
        intent.addCategory("aaa.bbb.ccc.ddd");
        intent.setPackage("bjpkten.aserver");
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                fighting = Fighting.Stub.asInterface(service);
                int add = 0;
                try {
                    add = fighting.add(10, 10);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Log.d("kodulf", "onServiceConnected: added = " + add);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        //boolean b = bindService(intent, conn, BIND_AUTO_CREATE);
        //Log.d("kodulf","bind result : " + b);

        doInCreate();
        getContentResolver().registerContentObserver(
                ContactsContract.Contacts.CONTENT_URI,
                true,
                mContentObserver);
        getContentResolver().registerContentObserver(
                Uri.parse("content://com.android.calendar/calendars"),
                true,
                mContentObserver);
        getContentResolver().registerContentObserver(
                Uri.parse("content://com.android.calendar/events"),
                true,
                mContentObserver);
        getContentResolver().registerContentObserver(
                Uri.parse("content://com.android.calendar/reminders"),
                true,
                mContentObserver);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        getContentResolver().unregisterContentObserver(mContentObserver);
    }

    public void add(View view) {
        int add = 0;
        try {
            add = fighting.add(100, 200);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        Log.d("kodulf", "add: " + add);
    }

    public void jump(View view) {
        startActivityForResult(new Intent(this,SecondActivity.class),100);
    }


    private void doInCreate() {
        // 检查该权限是否已经获取
        int i = ContextCompat.checkSelfPermission(this, permissions[0]);
        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
        if (i != PackageManager.PERMISSION_GRANTED) {
            // 如果没有授予该权限,就去提示用户请求
            showDialogTipUserRequestPermission();
        }

        Log.d("kodulf", "onCreate: " + i + "  "+(i != PackageManager.PERMISSION_GRANTED));

        // 检查该权限是否已经获取
        i = ContextCompat.checkSelfPermission(this, permissions[1]);
        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
        if (i != PackageManager.PERMISSION_GRANTED) {
            // 如果没有授予该权限,就去提示用户请求
            showDialogTipUserRequestPermission();
        }
        Log.d("kodulf", "onCreate: " + i + "  "+(i != PackageManager.PERMISSION_GRANTED));
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于支付宝需要获取存储空间,为你存储个人信息;\n否则,您将无法正常使用支付宝")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限

    private void showDialogTipUserGoToAppSettting() {

        dialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中,允许支付宝使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值