Android 學習筆記 BroadcastReceiver廣播...

來源:互聯網
上載者:User

標籤:

PS:不斷提升自己,是件好事...

學習內容:

1.BroadcastReceiver的使用..

2.通過BroadcastReceiver去啟動Service...

 

1.BroadcastReceiver...

  廣播接收者,用來接收系統和應用中的廣播...Android廣播機制用的地方還是很多的,比如說:當網路狀態發生改變的時候,通過接收這條廣播就能及時做出相應的響應,然後完成一些操作..這就是廣播的機制...它自身並不實現圖形化使用者介面...只是一個觸發性的操作...

  使用廣播是需要幾個步驟的...

i.那就是建立一個類來實現一個廣播,再類中定義響應的方法...來完成一些響應的操作...

ii.廣播這個東西是需要註冊的,不進行註冊是無法使用的....

註冊的方式有兩種:

                一種是靜態註冊,靜態註冊就是配置AndroidManifest.xml檔案進行配置,由系統管理receiver,屬於常駐型的...

<!--這段代碼添加在application之間就可以了。。。--><receiver android:name=".MyBroadcast"                  android:enabled="true">            <intent-filter>                <action android:name="android.intent.action.EDIT"/>            </intent-filter></receiver>

                          二種則是動態註冊...屬於非常駐型的,並且隱藏在代碼塊之間...不容易發現...

private BroadcastReceiver receiver;receiver=new CallReceiver();//動態註冊廣播位址...registerReceiver(receiver,new IntentFilter("android.intent.action.EDIT"));//解除註冊的廣播位址,一定要對廣播機制進行登出...unregisterReceiver(receiver);

iii.註冊完成後就是進行發送廣播了...這樣廣播接收者就可以正常工作了...先構建一個Intent對象,然後調用sendBroadcast(Intent)方法將廣播發出...

    還有一點就是,對象調用了onReceive()方法時廣播才是有效,當從這個函數返回之後,這個對象就無效了..因此廣播的生命週期是非常短暫的,也就僅僅十幾秒的生命週期,因此不要在其中加入一些耗時的操作,耗時的操作可以交給Service去完成,廣播就是完成一些非常小的操作就可以了...粘一個代碼...

package com.example.broadcast_receiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadcast extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        String str=intent.getStringExtra("msg");        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();    }}

上面就是定義一個廣播接收類,它繼承於BroadcastReceiver,在其中完成一些相應的操作....

package com.example.broadcast_receiver;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.content.Intent;public class MainActivity extends Activity implements View.OnClickListener {    private Intent intent=new Intent(Intent.ACTION_EDIT);    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        findViewById(R.id.broadcast).setOnClickListener(this);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public void onClick(View v) {        // TODO Auto-generated method stub        switch (v.getId()) {        case R.id.broadcast:            intent.putExtra("msg", "aa");            MainActivity.this.sendBroadcast(intent);            break;        }    }}

  這個就是如何在MainActivity中調用廣播接收者,很簡單的一個動作,就是觸發按鈕,然後會在螢幕上輸出"aa"這條資訊...很簡單的一個操作,布局檔案就一個按鈕,沒必要去粘貼...重要的是理解一下這個過程,不要忘了使用BroadcastReceiver時一定要進行註冊,否則是不能進行使用的....

2.如何使用BroadcastReceiver去啟動Service...

  前面已經說過,BroadcastReceiver對象的生命週期是非常短暫的...那麼耗時的動作是無法在這裡執行的,但是我們可以在BroadcastReceiver中去調用Service...讓Service去執行耗時的服務...簡單的介紹一下如何去啟動Service...

i.首先我們先定義一個Service...

package com.example.broadcast_receiver;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;public class MyService extends Service{    private MediaPlayer media;    @Override    public IBinder onBind(Intent intent) {        // TODO Auto-generated method stub        return null;    }    @Override    public void onCreate(){        super.onCreate();        media=MediaPlayer.create(MyService.this, R.raw.a);        MyService.this.media.prepare();        MyService.this.media.start();        media.setLooping(true);    }    @Override    public void onDestroy(){        super.onDestroy();    }    @Override    public void onStart(Intent intent,int startId){        super.onStart(intent, startId);    }}

這裡我們需要複製一首歌曲到res\raw檔案夾下一首歌曲...raw檔案夾我們自己進行建立...

package com.example.broadcast_receiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadcast extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub        Intent newintent =new Intent(context,MyService.class);        context.startService(newintent);        String str=intent.getStringExtra("msg");        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();    }  }

     這個是廣播類,從廣播的內部去啟動Service.....然後在AndroidManifest.xml檔案中的<application>和</application>之間加入代碼<service android:name=".MyService" android:enable="true"/>就搞定了...

  這樣就完成了在BroadcastReceiver()內部去啟動Service.....

 

 

 

 

 

 

                 

 

Android 學習筆記 BroadcastReceiver廣播...

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.