Android0908(部分Service、 ContentProvider、 BroadcastReceiver)

ContentProvider

內容提供器(ContentProvider)主要用於不同的應用程序之間實現數據共享的功能

要訪問共享的數據,就一定要藉助ContentResolver類,可以通過getContentResolver()方法或得該類的實例,通過這個方法提供的方法可以對共享的數據進行增刪改查,ContentProvider中的增刪改查方法都不接收表名參數而是通過一個Uri參數代替,這個參數稱爲內容的URI。內容URI由兩部分組成,權限(authority)和路徑(path)。權限用於對不同的應用程序作區分,用包名命名權限,例如包名爲:com.example.app,那麼程序對應的權限名稱爲com.example.app.provider

resolver = getContentResolver();
                Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursor=resolver.query(uri,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER,
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},null,null,null);
                cursor.moveToFirst();

例如想要訪問電話薄裏的聯繫人信息,就需要聲明權限,就需要在AndroidManifest.XML中增加一條代碼如下:

    <uses-permission android:name="android.permission.READ_CONTACTS"/>

還有在ContentResolver的query()方法來查詢系統的聯繫人數據。傳入的參數ContactsContract.CommonDataKinds.Phone類已經封裝好了,提供了一個.CONTENT_URI常量,聯繫人名字對應的常量是
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,聯繫人手機號對應的常量是ContactsContract.CommonDataKinds.Phone.NUMBER

具體的實例:ContentResolve.java

package com.example.administrator.controlapplication;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
 * Created by Administrator on 2015/9/8.
 */
public class ContentResolver extends Activity{
    private Button btn_read;
    private android.content.ContentResolver resolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contentresolver);
        btn_read= (Button) findViewById(R.id.readfriends);
        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resolver = getContentResolver();
                Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursor=resolver.query(uri,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER,
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},null,null,null);
                cursor.moveToFirst();
                while(!cursor.isAfterLast()){
                    String []names=cursor.getColumnNames();
                    StringBuffer buffer=new StringBuffer();
                    for(String name:names){
                        String value=cursor.getString(cursor.getColumnIndex(name));
                        buffer.append("字段名"+name+"  字段值"+value);
                    }
                    Log.d("聯繫人",""+buffer);
                    cursor.moveToNext();
                }
            }
        });
    }
}

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

BroadcastReceiver

BroadcastReceiver是一種廣播接收器
這裏寫圖片描述
這裏寫圖片描述
廣播接收器需要在要接受的廣播進行註冊,才能在廣播發出時,廣播接收器能夠接受到廣播,註冊廣播分爲兩種,在代碼中註冊和在
AndroidManifest.xml中註冊,前者是動態註冊,後者是靜態註冊

靜態的註冊廣播

首先新建一個簡單的繼承於BroadcastReceiver的類,如下:

public class BroadcastReceiverActivity extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"我接收到了廣播",Toast.LENGTH_SHORT).show();
    }
}

然後再AndroidManifest.xml中< application>標籤中添加一個新的標籤< receiver>,所有的靜態的註冊廣播接收器都在這裏,通過一個< android:name>來制定註冊拿一個廣播接收器,然後在< infent-filter>標籤里加入想要加入的廣播就行了,如下:

<receiver android:name=".BroadcastReceiverActivity">
            <intent-filter>
                <action android:name="com.myreceiver.test"></action>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
                <action android:name="android.intent.action.PACKAGE_REMOVED"></action>
                </intent-filter>
        </receiver>

動態的註冊廣播

動態的註冊廣播,在代碼裏實現,創建一個IntentFilter和BroadcastReceiverActivity的實例,調用registerReceiver(),然後將這兩個實例對象傳進去

 mBroadcast=new BroadcastReceiverActivity();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.myreceiver.test");
        registerReceiver(mBroadcast,filter);

動態註冊的廣播接收器一定都要取消註冊纔行,要在onDestroy()中通過調用unregisterReceiver()方法來實現。

 @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcast);
    }

在AndroidManifest.xml中加入

<receiver android:name=".BroadcastReceiverActivity">
            <intent-filter>  
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
                <action android:name="android.intent.action.PACKAGE_REMOVED"></action>
                </intent-filter>
        </receiver>

自定義的廣播MainActivity.java

public class MainActivity extends Activity {
    private Button btn_receiver;
    private android.content.ContentResolver resolver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_receiver= (Button) findViewById(R.id.receiver);
        btn_receiver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction("com.myreceiver.test");
                sendBroadcast(intent);
            }
        });  
}

BroadcastReceiverActivity.java

public class BroadcastReceiverActivity extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"我接收到了廣播",Toast.LENGTH_SHORT).show();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.controlapplication" >
    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/youtube_ico"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ContentResolver"
            android:label="ContentResolver" >
            </activity>
        <receiver android:name=".BroadcastReceiverActivity">
            <intent-filter>
                <action android:name="com.myreceiver.test"></action>            
                </intent-filter>
        </receiver>

    </application>

</manifest

這裏寫圖片描述

簡單地設置鬧鐘

利用廣播機制可以簡單地設置鬧鐘,可以通過getBroadcast(Context context, int requestCode, Intent intent, int flags)從系統取得一個用於向BroadcastReceiver的Intent廣播的PendingIntent對象
1、context 將在這個PendingIntent 的內容context 進行廣播
2、requestCode 發送端的私人請求碼(目前未使用)。
3、intent 被廣播的Intent
4、flags 可以
flag_one_shot,flag_no_create,flag_cancel_current,flag_update_current,或任何的旗幟支持byintent。fillin()控制指定部分的意圖,可以提供實際發生時發送。
FLAG_CANCEL_CURRENT:如果當前系統中已經存在一個相同的PendingIntent對象,那麼就將先將已有的PendingIntent取消,然後重新生成一個PendingIntent對象。

調用AlarmManager的setRepeating()方法設置鬧鐘的顯示時間

type:表示警報類型,一般可以取的值是AlarmManager.RTC和AlarmManager.RTC_WAKEUP。如果將type參數值設爲AlarmManager.RTC,表示是一個正常的定時器,如果將type參數值設爲AlarmManager.RTC_WAKEUP,除了有定時器的功能外,還會發出警報聲(例如,響鈴、震動)。

triggerAtTime:第1次運行時要等待的時間,也就是執行延遲時間,單位是毫秒。

interval:表示執行的時間間隔,單位是毫秒。

operation:一個PendingIntent對象,表示到時間後要執行的操作。PendingIntent與Intent類似,可以封裝Activity、BroadcastReceiver和Service。但與Intent不同的是,PendingIntent可以脫離應用程序而存在。

PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplication(),0x23,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,3000,pendingIntent);

當然需要不想鬧鐘一直響,就需要一個取消鬧鐘的方法,只需調用AlarmManager的cancel()方法即可。

 Intent intent=new Intent();
                intent.setAction("com.myreceiver.test");
                PendingIntent pendingIntent=PendingIntent.getBroadcast(getApplication(),0x23,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                mAlarmManager.cancel(pendingIntent);

BroadcastReceiverActivity .java

public class BroadcastReceiverActivity extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"鬧鐘響了,該起牀了",Toast.LENGTH_SHORT).show();
    }
}

這裏寫圖片描述

Service

這裏寫圖片描述

Service需要在AndroidManifest.xml中進行註冊

<service android:name=".MyService"></service>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.controlapplication" >
    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/youtube_ico"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ContentResolver"
            android:label="ContentResolver" >
            </activity>
        <receiver android:name=".BroadcastReceiverActivity">
            <intent-filter>
                <!--<action android:name="com.myreceiver.test"></action>-->
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
                <action android:name="android.intent.action.PACKAGE_REMOVED"></action>
                </intent-filter>
        </receiver>
        <service android:name=".MyService"></service>
        <service android:name=".MyIntentService"></service>
    </application>
</manifest>

首先要寫一個繼承於Service的類,
MyService.java

public class MyService extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("運行到了","onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("運行到了","onDestroy");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("運行到了","onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }
}

MainActivity.java

public class MainActivity extends Activity {
    private Button btn_start_service;
    private Button btn_stop_service;   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);      
        btn_start_service= (Button) findViewById(R.id.start_service);
        btn_start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                startService(intent);
            }
        });
        btn_stop_service= (Button) findViewById(R.id.stop_service);
        btn_stop_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });
    }

BroadcastReceiverActivity.java

public class BroadcastReceiverActivity extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"確定要刪除了此應用嗎",Toast.LENGTH_SHORT).show();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章