intent 和 Broadcast Receiver之間的通訊

工做原理是經過封裝一個service啓動的一個線程產生的隨機數封裝到intent對象傳遞給Activity,Activity接受到後講結果輸出到屏幕。

java的代碼:

package jm.out;
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.view.View.OnClickListener;//引入相關包
import android.widget.Button;//引入相關包
import android.widget.TextView;//引入相關包
//繼承自Activity的子類
public class IntentBroadcastActivity extends Activity {
 public static final int CMD_STOP_SERVICE = 0;
 Button btnStart;//開始服務Button對象應用
 Button btnStop;//中止服務Button對象應用
 TextView tv;//TextView對象應用
 DataReceiver dataReceiver;//BroadcastReceiver對象
 @Override
    public void onCreate(Bundle savedInstanceState) {//重寫onCreate方法
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//設置顯示的屏幕
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        tv = (TextView)findViewById(R.id.tv);
        btnStart.setOnClickListener(new OnClickListener() {//爲按鈕添加點擊事件監聽  
   @Override
   public void onClick(View v) {//重寫onClick方法
    Intent myIntent = new Intent(IntentBroadcastActivity.this, jm.out.MyService.class);
    IntentBroadcastActivity.this.startService(myIntent);//發送Intent啓動Service
   }
  });
        btnStop.setOnClickListener(new OnClickListener() {//爲按鈕添加點擊事件監聽 
   @Override
   public void onClick(View v) {//重寫onClick方法
    Intent myIntent = new Intent();//建立Intent對象
    myIntent.setAction("wyf.wpf.MyService");
    myIntent.putExtra("cmd", CMD_STOP_SERVICE);
    sendBroadcast(myIntent);//發送廣播
   }
  });
    } 
 private class DataReceiver extends BroadcastReceiver{//繼承自BroadcastReceiver的子類
  @Override
  public void onReceive(Context context, Intent intent) {//重寫onReceive方法
   double data = intent.getDoubleExtra("data", 0);
   tv.setText("Service的數據爲:"+data);   
  }  
 }
 @Override
 protected void onStart() {//重寫onStart方法
  dataReceiver = new DataReceiver();
  IntentFilter filter = new IntentFilter();//建立IntentFilter對象
  filter.addAction("wyf.wpf.Sample_3_6");
  registerReceiver(dataReceiver, filter);//註冊Broadcast Receiver
  super.onStart();
 }
 @Override
 protected void onStop() {//重寫onStop方法
  unregisterReceiver(dataReceiver);//取消註冊Broadcast Receiver
  super.onStop();
 }
}

service類:

package jm.out;

import android.app.Service;//引入相關包
import android.content.BroadcastReceiver;//引入相關包
import android.content.Context;//引入相關包
import android.content.Intent;//引入相關包
import android.content.IntentFilter;//引入相關包
import android.os.IBinder;//引入相關包
//繼承自Service的子類
public class MyService extends Service{
 CommandReceiver cmdReceiver;
 boolean flag;
 @Override
 public void onCreate() {//重寫onCreate方法
  flag = true;
  cmdReceiver = new CommandReceiver();
  super.onCreate();
 }
 @Override
 public IBinder onBind(Intent intent) {//重寫onBind方法
  // TODO Auto-generated method stub
  return null;
 }
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {//重寫onStartCommand方法
  IntentFilter filter = new IntentFilter();//建立IntentFilter對象
  filter.addAction("jm.out.MyService");
  registerReceiver(cmdReceiver, filter);//註冊Broadcast Receiver
  doJob();//調用方法啓動線程
  return super.onStartCommand(intent, flags, startId);
 }
 //方法:
 public void doJob(){
  new Thread(){
   public void run(){
    while(flag){
     try{//睡眠一段時間
      Thread.sleep(1000);
     }
     catch(Exception e){
      e.printStackTrace();
     }
     Intent intent = new Intent();//建立Intent對象
     intent.setAction("jm.out.IntentBroadcastActivity");
     intent.putExtra("data", Math.random());
     sendBroadcast(intent);//發送廣播
    }    
   }
   
  }.start();
 } 
 private class CommandReceiver extends BroadcastReceiver{//繼承自BroadcastReceiver的子類
  @Override
  public void onReceive(Context context, Intent intent) {//重寫onReceive方法
   int cmd = intent.getIntExtra("cmd", -1);//獲取Extra信息
   if(cmd == IntentBroadcastActivity.CMD_STOP_SERVICE){//若是發來的消息是中止服務    
    flag = false;//中止線程
    stopSelf();//中止服務
   }
  }  
 }
 @Override
 public void onDestroy() {//重寫onDestroy方法
  this.unregisterReceiver(cmdReceiver);//取消註冊的CommandReceiver
  super.onDestroy();
 } 
}

xml配置:

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
  <Button android:id="@+id/btnStart"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="啓動服務" />
  <Button android:id="@+id/btnStop"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="中止服務" />
  <TextView android:id="@+id/tv"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="等待來自Service的數據" />
  </LinearLayout>

androidmanifest.xml的配置:

  <?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="wyf.wpf" android:versionCode="1" android:versionName="1.0">
-<application android:icon="@drawable/icon" android:label="@string/app_name">
-<activity android:name=".Sample_3_6" android:label="@string/app_name">
-<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
  </activity>
-<service android:name=".MyService" android:process=":remote">
-<intent-filter>
 <actionandroid:name="wyf.wpf.MyService" />
  </intent-filter>
  </service>
  </application>
  <uses-sdk android:minSdkVersion="7" />
  </manifest>
要注意的是紅色代碼,只有這樣纔可讓service在activity退出後還能運行,保證了主線程中止,service還能在後臺運行。 
相關文章
相關標籤/搜索