總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。
顯示具有 BroadcastReceiver 標籤的文章。 顯示所有文章
顯示具有 BroadcastReceiver 標籤的文章。 顯示所有文章

2014年7月1日 星期二

為自己的AP增加發/收BroadcastReceiver事件







一陣子沒碰還是會忘記 BroadcastReceiver 怎麼做, 今天又重新整理了一下

首先在要接收封包事件的class新增一個class
在此範例中是寫在主程式(extends Activity)
public class BroadcastReceiver_customize extends BroadcastReceiver {

        //定義封包來源

        static final String PieFee_ACTION = "com.tsots.PieFee";

        @Override

        public void onReceive(Context context, Intent intent) {

            //若封包符合PieFee_ACTION內的值就接收下來

            if (intent.getAction().equals(PieFee_ACTION)) {

                Bundle bundle_from = intent.getExtras();

                if (bundle_from != null){

                    //解析封包內的"FROM"值

                    from = bundle_from.getString("FROM");

                    if(from.equals("prizeexchanged")){

                        //這裡是接收到Broadcast後要做的事

                    }

                }

            }                                   

        }

    } 


在主程式(extends Activity) 的onResume()中增加
@Override

    protected void onResume() {

        super.onResume();

        //註冊一個Filter

        IntentFilter mFilter = new IntentFilter(BroadcastReceiver_customize.PieFee_ACTION);

        BroadcastReceiver_customize BRC = new BroadcastReceiver_customize();

        registerReceiver(BRC, mFilter);

    } 


再來決定發送端
在此範例中是寫在一個extends BaseAdapter的class裡
//會將封包以 "com.tsots.PieFee"的名義發送

Intent intent = new Intent("com.tsots.PieFee");

Bundle bundle_br_prize = new Bundle();

//在其內打包一個值作為識別

bundle_br_prize.putString("FROM", "prizeexchanged");

intent.putExtras(bundle_br_prize); 

//因為此class非extends Activity, 故加context(呼叫此class時會傳入context的值)

context.sendBroadcast(intent);


2012年3月5日 星期一

Filter Broadcast List

addDataScheme addAction

ACTION_BATTERY_CHANGED 當電量產生變化

ACTION_BATTERY_LOW 電量低

ACTION_BATTERY_OKAY 電量正常

ACTION_POWER_CONNECTED 連接充電

ACTION_POWER_DISCONNECTED 拔除充電

ACTION_BOOT_COMPLETED 開機完成

ACTION_REBOOT 重新啟動

ACTION_SHUTDOWN 關機

ACTION_SCREEN_OFF 螢幕關閉

ACTION_SCREEN_ON 螢幕開啟

ACTION_CAMERA_BUTTON 當按下Camera按鈕

ACTION_HEADSET_PLUG 耳機被插上或拔下

ACTION_CONFIGURATION_CHANGED Configuration(orientation, locale...) 螢幕旋轉

ACTION_DATE_CHANGED 當日期改變

ACTION_INPUT_METHOD_CHANGED 輸入法改變

ACTION_LOCALE_CHANGED 地區改變

ACTION_TIMEZONE_CHANGED 時區改變

ACTION_TIME_CHANGED 時間改變

ACTION_TIME_TICK 時間被變更

ACTION_WALLPAPER_CHANGED 當桌布變更

ACTION_GTALK_SERVICE_CONNECTED Gtalk連線建立

ACTION_GTALK_SERVICE_DISCONNECTED Gtalk連線中斷
file ACTION_MEDIA_MOUNTED SDCard掛載
ACTION_MEDIA_UNMOUNTED SDCard 移除

ACTION_NEW_OUTGOING_CALL 播打電話
package ACTION_PACKAGE_ADDED 安裝一個新的程式
ACTION_PACKAGE_CHANGED 即有的程式被變更
ACTION_PACKAGE_DATA_CLEARED 程式的資料被清除
ACTION_PACKAGE_FIRST_LAUNCH 程式第一次被執行
ACTION_PACKAGE_RESTARTED 程式被重新執行
ACTION_PACKAGE_INSTALL 安裝程式
ACTION_PACKAGE_REMOVED 程式移除
ACTION_PACKAGE_REPLACED 程式被取代

ACTION_UMS_CONNECTED USB Mount

ACTION_UMS_DISCONNECTED USB Unmount

ACTION_USER_PRESENT wake up

2012年2月29日 星期三

偵測APK install / uninstall 所發出的Broadcast事件

當有AP被install / uninstall時,
系統會發出Broadcast :ACTION_PACKAGE_ADDED / ACTION_PACKAGE_REMOVED,
假設我們在APP List的畫面中,
希望能"即時"的在AP有新增/移除時變更於Activity,
就需要建立BroadcastReceiver

=======================方法一:不用新增class也不用在Manifest.xml中宣告=======================
@Override
protected void onResume()
{
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_PACKAGE_ADDED);     //只能接收用adb install的安裝事件
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);//只能接收用adb uninstall的反安裝事件
    filter.addDataScheme("package");
    mIntentReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {               
            final String action = intent.getAction();
            if (Intent.ACTION_PACKAGE_ADDED.equals(action))
            {               

                Uri data = intent.getData();
                String pkgName = data.getEncodedSchemeSpecificPart();
                //pkgName被安裝AP的package name, 在存入SQLite時必須要的資訊

                queryAPInfo();
                Toast.makeText(context, "ACTION_PACKAGE_ADDED", Toast.LENGTH_SHORT).show();
            }
            else if (Intent.ACTION_PACKAGE_REMOVED.equals(action))
           {
                queryAPInfo();
                Toast.makeText(context, "ACTION_PACKAGE_REMOVED", Toast.LENGTH_SHORT).show();
            }
        }
    };       
registerReceiver(mIntentReceiver, filter);

super.onResume();
}

@Override
protected void onPause()
{
    context.unregisterReceiver(mIntentReceiver);
    super.onPause();
}

//改一下queryAPInfo()
//此function所做的: 重新查一遍package的資料, 並setAdapter()更新畫面
public void ArrayList<String> queryAPInfo()
{
    for(int i = 0 ; i <allappPagInfo.size() ; i ++)
    {              
        list_apPag = new ArrayList<String>();
        list_apName = new ArrayList<String>(); 
        PackageInfo appPI = allappPagInfo.get(i); //PackageInfo{2ad3d2e0 com.android.launcher}
        String apPag = appPI.packageName;         //com.android.launcher
        list_apPag.add(apPag);
        String apName = appPI.applicationInfo.loadLabel(packageManager).toString(); //Launcher
        list_apName.add(apName);   
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_apName);
    GridView gridView1 = (GridView) findViewById (R.id.gridView1);
    gridView1.setAdapter(adapter);
}

 =======================方法二:新增class且要在Manifest.xml中宣告=======================
1. adb uninstall
2. User在Device上操作解除安裝
都可以偵測到 
./AndroidManifest.xml
<receiver android:name=".PackageReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_ADDED" />
        <action android:name="android.intent.action.PACKAGE_REMOVED" />
        <data android:scheme="package" />
     </intent-filter>
</receiver>

./src/com.tsots.AppManager/Activity.java
package com.tsots.AppManager;
public class Activity extends Activity
{
    protected void onCreate(Bundle icicle) 
    {
        .....
    }

    @Override
    protected void onResume()
    {
        PackageReceiver BRC = new PackageReceiver();
        IntentFilter mFilter1, mFilter2;
        //過濾PACKAGE_ADDED與PACKAGE_REMOVED事件
        mFilter1 = new IntentFilter(BRC.addpk_ACTION);
        mFilter2 = new IntentFilter(
BRC.removepk_ACTION);
        mFilter1.addDataScheme("package");
        mFilter2.addDataScheme("package");
        //註冊Receiver     
        registerReceiver(BRC, mFilter1);
        registerReceiver(BRC, mFilter2);

        super.onResume();
    }

    public class PackageReceiver extends BroadcastReceiver
    {
        private static final String addpk_ACTION = "android.intent.action.PACKAGE_ADDED";
        private static final String removepk_ACTION = "android.intent.action.PACKAGE_REMOVED";       
 
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction().equals(addpk_ACTION))
            {       
                Uri data = intent.getData();
                String pkgName = data.getEncodedSchemeSpecificPart();

                //pkgName為package名稱
                Intent iSend = new Intent(addpk_ACTION);

                //送出廣播 
                context.sendBroadcast(iSend);
            }         
            else if (intent.getAction().equals(removepk_ACTION))
            {               
                Uri data = intent.getData();
                String pkgName = data.getEncodedSchemeSpecificPart();

                //pkgName為package名稱 
                Intent iSend = new Intent(removepk_ACTION);

                //送出廣播
                context.sendBroadcast(iSend);
            }
        }
    }

}

2012年1月26日 星期四

BroadcastReceiver ~ 自訂IntentFilter監聽電量、開機、簡訊事件








Activity_main.java

package com.tsots.Compare_BroadcastReceiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Activity_main extends Activity 
{
	Button b1;
	TextView tv1, tv2, tv3;
	String from = "There is no BroadcastReceiver yet";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1 = (Button) findViewById (R.id.button1);

        tv1 = (TextView) findViewById (R.id.textview1);
        tv2 = (TextView) findViewById (R.id.textview2);
        tv3 = (TextView) findViewById (R.id.textview3);

        /*
         * 透過Intent.ACTION_BATTERY_CHANGED取得battery資訊
         */
        b1.setOnClickListener(new Button.OnClickListener()
        {
			public void onClick(View v) 
			{
				BroadcastReceiver_Battery br = new BroadcastReceiver_Battery();	
				registerReceiver(br, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
			}        	
        });
    }
 
    /*
     * 過濾從以下class傳來的封包
     * BroadcastReceiver_Battery.java
     * BroadcastReceiver_Boot.java
     * BroadcastReceiver_SMS.java
     */
    @Override
	protected void onResume() 
	{
		super.onResume();
		try
    	{
	    	IntentFilter mFilter1, mFilter2, mFilter3;
	    	mFilter1 = new IntentFilter(BroadcastReceiver_Battery.customize_ACTION);
	    	mFilter2 = new IntentFilter(BroadcastReceiver_Boot.customize_ACTION);
	    	mFilter3 = new IntentFilter(BroadcastReceiver_SMS.customize_ACTION);
	    	BroadcastReceiver_customize BRC = new BroadcastReceiver_customize();
	    	registerReceiver(BRC, mFilter1);
	    	registerReceiver(BRC, mFilter2);
	    	registerReceiver(BRC, mFilter3);
    	}
    	catch(Exception e)
    	{
    		
    	}
	}
	
    /*
     * 透過自訂的BroadcastReceiver擷取從以下class傳來的封包
     * BroadcastReceiver_Battery.java
     * BroadcastReceiver_Boot.java
     * BroadcastReceiver_SMS.java
     * 並取得存在Service的資訊
     */
    public class BroadcastReceiver_customize extends BroadcastReceiver 
    {
    	static final String customize_ACTION = "com.tsots.Compare_BroadcastReceiver.CUSTOMIZE";
    	@Override
    	public void onReceive(Context context, Intent intent) 
    	{
    		if (intent.getAction().equals(customize_ACTION)) 
    	    {
    	        Bundle bundle_from = intent.getExtras();
    	        if (bundle_from != null)
    	        {
    	        	from = bundle_from.getString("FROM");
    	        }
    	    }
    		System.out.println(from);
    		if(from.equals("the BroadcastReceiver is from BroadcastReceiver_Battery"))
    		{
    			tv1.setText(new Service_receiveBR().str_battery);
    		}
    		else if(from.equals("the BroadcastReceiver is from BroadcastReceiver_Boot"))
    		{
    			tv2.setText(new Service_receiveBR().str_boot);
    		}
    		else
    		{
    			tv3.setText(new Service_receiveBR().str_sms);
    		}    		    		    		
    	}
    }
}

BroadcastReceiver_SMS.java

package com.tsots.Compare_BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class BroadcastReceiver_SMS extends BroadcastReceiver 
{
	private static final String sms_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	static final String customize_ACTION = "com.tsots.Compare_BroadcastReceiver.CUSTOMIZE";
	@Override
	public void onReceive(Context context, Intent intent) 
	{
	    if (intent.getAction().equals(sms_ACTION)) 
	    { 
	      StringBuilder sb = new StringBuilder(); 
	      Bundle bundle = intent.getExtras(); 
	      if (bundle != null) 
	      { 
	        Object[] myOBJpdus = (Object[]) bundle.get("pdus"); 
	        SmsMessage[] messages = new SmsMessage[myOBJpdus.length];  
	        for (int i = 0; i

BroadcastReceiver_Boot.java
package com.tsots.Compare_BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class BroadcastReceiver_Boot extends BroadcastReceiver 
{
	private static final String boot_ACTION = "android.intent.action.BOOT_COMPLETED";
	static final String customize_ACTION = "com.tsots.Compare_BroadcastReceiver.CUSTOMIZE";
	//取得系統時間
	java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		if (intent.getAction().equals(boot_ACTION)) 
	    {
	        StringBuilder sb = new StringBuilder(); 
		    sb.append("開機時間: ");   
		    sb.append(sdf.format(new java.util.Date()));
	        Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();

	        //啟動Service服務並將boot資訊傳過去
	        intent.setClass(context, Service_receiveBR.class);
		    Bundle bundle_br_boot = new Bundle();
		    bundle_br_boot.putString("MESSAGE_BOOT", sb.toString());
		    intent.putExtras(bundle_br_boot);
		    context.startService(intent);
	        
		    //送出廣播"android.intent.action.BOOT_COMPLETED"
		    Intent intent_BroadcastToActivity = new Intent(customize_ACTION);
		    intent_BroadcastToActivity.putExtra("FROM", "the BroadcastReceiver is from BroadcastReceiver_Boot");
		    context.sendBroadcast(intent_BroadcastToActivity);
	    }
	}
}
BroadcastReceiver_Battery.java
package com.tsots.Compare_BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class BroadcastReceiver_Battery extends BroadcastReceiver 
{
	private static final String battery_ACTION = "android.intent.action.BATTERY_CHANGED";
	public static final String customize_ACTION ="com.tsots.Compare_BroadcastReceiver.CUSTOMIZE";
	private int intLevel;
	private int intScale; 
	
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		if (intent.getAction().equals(battery_ACTION)) 
	    {
			//level: 電池剩餘容量
			intLevel = intent.getIntExtra("level", 0);
			//scale: 電池最大值;通常為100
	        intScale = intent.getIntExtra("scale", 100); 

	        StringBuilder sb = new StringBuilder(); 
		    Bundle bundle = intent.getExtras(); 
		    if (bundle != null) 
		    { 
		    	sb.append("目前電量:");
		        sb.append(String.valueOf(intLevel * 100 / intScale) + "%");   
		    } 
	        Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
	        
	        //啟動Service服務並將battery資訊傳過去
	        intent.setClass(context, Service_receiveBR.class);
		    Bundle bundle_br_battery = new Bundle();
		    bundle_br_battery.putString("MESSAGE_BATTERY", sb.toString());
		    intent.putExtras(bundle_br_battery);
		    context.startService(intent);
		    
		    //送出廣播"android.intent.action.BOOT_COMPLETED"
		    Intent intent_BroadcastToActivity = new Intent(customize_ACTION);
		    intent_BroadcastToActivity.putExtra("FROM", "the BroadcastReceiver is from BroadcastReceiver_Battery");
		    context.sendBroadcast(intent_BroadcastToActivity);
	    }
	}
}
Service_receiveBR.java
package com.tsots.Compare_BroadcastReceiver;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

/*
 * 用此Service存住battery,boot,SMS的資訊
 */
public class Service_receiveBR extends Service
{
	static String str_battery;
	static String str_boot;
	static String str_sms;
	@Override
	public void onCreate() 
	{
		super.onCreate();		
	}
	
	@Override
	public void onStart(Intent intent, int startId) 
	{		
		Bundle bundle = intent.getExtras();
		if(bundle != null)
		{
			str_battery = bundle.getString("MESSAGE_BATTERY");
			str_boot = bundle.getString("MESSAGE_BOOT");
			str_sms = bundle.getString("MESSAGE_SMS");
		}
		super.onStart(intent, startId);		
	}

	@Override
	public IBinder onBind(Intent arg0) 
	{
		// TODO Auto-generated method stub
		return null;
	}	
}