android中的通信機制總結

第一種:使用handler來進行通信
   handler 大家可以把它想象成主線程(UI線程)的一個子線程,它可以給主線程(UI線程)發送數據從而更新主線程(UI線程)的UI與邏輯,handler 是一個子線程所以它的耗時操作不會阻塞主線程,大家都知道在android的開發中如果代碼中某個地方阻塞主線程超過5秒的話系統會提示ANR (系統提示強制關閉)所以在耗時操作上我們可以考慮開啓一個子線程避免ANR。  handler會向主線程發送消息 會以隊列的形式排列着配合等待主線程更新UI 邏輯 等等。

[java] view plaincopy

  1. public class HandlerActivity extends Activity implements Runnable{    

  2.     

  3.     /**更新時間**/    

  4.     public final static int UPDATE_TIME =0;    

  5.     /**更新時間成功**/    

  6.     public final static int UPDATE_COMPLETED =1;    

  7.         

  8.     /**記錄顯示時間 超過10秒結束線程**/    

  9.     private int mShowNumber = 0;    

  10.         

  11.     /**開始計時按鈕**/    

  12.     private Button mButton = null;    

  13.         

  14.     /**計時顯示內容**/    

  15.     private TextView mTextView = null;    

  16.        

  17.     /**線程**/    

  18.     private Thread mThread = null;    

  19.        

  20.     /**線程關閉的標誌**/    

  21.     private boolean mRunning = false;    

  22.         

  23.     Handler handler = new Handler() {    

  24.     @Override    

  25.     public void handleMessage(Message msg) {    

  26.             

  27.         Bundle bundle= msg.getData();    

  28.         //通過key的名稱拿到它的值    

  29.         String  number = bundle.getString("number");    

  30.         //msg.what爲handler接收到的消息編號    

  31.         switch(msg.what) {    

  32.         case UPDATE_TIME:    

  33.         mTextView.setText("正在更新時間" + number);    

  34.         break;    

  35.         case UPDATE_COMPLETED:    

  36.         mTextView.setText("更新完畢");    

  37.         break;    

  38.         }    

  39.         super.handleMessage(msg);    

  40.     }    

  41.     };    

  42.     

  43.     @Override    

  44.     protected void onCreate(Bundle savedInstanceState) {    

  45.     setContentView(R.layout.handler);    

  46.         

  47.     /**拿到button 與  TextView 對象**/    

  48.     mButton = (Button)findViewById(R.id.button0);    

  49.     mTextView = (TextView)findViewById(R.id.textView0);    

  50.     mThread = new Thread(this);    

  51.         

  52.     mButton.setOnClickListener(new OnClickListener() {    

  53.         @Override    

  54.         public void onClick(View arg0) {    

  55.         /**點擊按鈕後開始線程開始計時**/    

  56.         mRunning = true;    

  57.         mThread.start();    

  58.         }    

  59.     });    

  60.         

  61.     mTextView.setText("點擊按鈕開始更新時間");    

  62.     super.onCreate(savedInstanceState);    

  63.     }    

  64.     

  65.     public void ShowDialog(String string) {    

  66.     AlertDialog.Builder builder = new AlertDialog.Builder(    

  67.         HandlerActivity.this);    

  68.     builder.setIcon(R.drawable.icon);    

  69.     builder.setTitle(string);    

  70.     builder.setPositiveButton("確定"new DialogInterface.OnClickListener() {    

  71.         public void onClick(DialogInterface dialog, int whichButton) {    

  72.         finish();    

  73.         }    

  74.     });    

  75.     builder.show();    

  76.     }    

  77.     

  78.      

  79.     

  80.     @Override    

  81.     public void run() {    

  82.     

  83.     while (mRunning) {    

  84.         try {    

  85.         mShowNumber++;    

  86.         /** 把須要的數據放入bandle中 **/    

  87.         Bundle bandle = new Bundle();    

  88.         bandle.putString("number", String.valueOf(mShowNumber));    

  89.     

  90.         /** 設置這條信息的編號爲更新時間 **/    

  91.         /** 將bandle寫入message中 **/    

  92.         /** 最後將這個message發送出去 **/    

  93.         /** mShowNumber小於10更新時間 否則更新完畢 **/    

  94.         Message msg = new Message();    

  95.         if(mShowNumber <=10) {    

  96.             msg.what = UPDATE_TIME;     

  97.         }else {    

  98.             mRunning = false;    

  99.             msg.what = UPDATE_COMPLETED;      

  100.         }    

  101.         msg.setData(bandle);    

  102.         handler.sendMessage(msg);    

  103.         Thread.sleep(1000);    

  104.         } catch (InterruptedException e) {    

  105.         e.printStackTrace();    

  106.         }    

  107.     }    

  108.     }    

  109. }    


2.Notifation通知欄信息
       Notifation通知欄會在屏幕上方向用戶提示信息 但是不會打斷用戶正在閱讀的內容,除非用戶手動將 Notifation通知欄拉下。 Notifation的好處就是在於不會影響用戶的操作,比如用戶正在閱讀非常重要的信息這時候幫他直接打開一個activity會非常不合適 因爲直接影響到了他當時的操作行爲 所以Notifation就出來了。建議大家在開發中遇到可能打斷用戶使用的情況下都去使用Notifation通知欄。

[java] view plaincopy

  1. public class NotificationActivity extends Activity {    

  2.     NotificationManager mManager = null;    

  3.     Notification notification =null;    

  4.     @Override    

  5.     protected void onCreate(Bundle savedInstanceState) {    

  6.     setContentView(R.layout.notification);    

  7.     

  8.     // 得到通知消息的管理器對象,負責管理 Notification 的發送與清除消息等    

  9.     mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    

  10.     // 創建Notification對象 參數分別代表 通知欄 中顯示的圖標 顯示的標題 顯示的時間    

  11.     notification = new Notification(R.drawable.jay,    

  12.         "Android專業開發羣", System.currentTimeMillis());    

  13.         

  14.     // 設置在通知欄中點擊後Notification自動消失    

  15.     notification.flags = Notification.FLAG_AUTO_CANCEL;    

  16.         

  17.     //設置點擊後轉跳的新activity    

  18.     Intent intent = new Intent(this, MyShowActivity.class);    

  19.     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);    

  20.     

  21.     //通過bundle可以帶一些數據過去 這裏將字符串傳遞了過去    

  22.     Bundle bundle = new Bundle();    

  23.     bundle.putString("name""從Notification轉跳過來的");    

  24.     intent.putExtras(bundle);    

  25.         

  26.     //設置通知欄中顯示的內容    

  27.     PendingIntent contentIntent = PendingIntent.getActivity(this,    

  28.         R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);    

  29.     notification.setLatestEventInfo(this"Android專業開發羣",    

  30.         "QQ羣號 164257885", contentIntent);    

  31.         

  32.     

  33.     Button button0 = (Button)findViewById(R.id.button0);    

  34.     button0.setOnClickListener(new OnClickListener() {    

  35.             

  36.         @Override    

  37.         public void onClick(View arg0) {    

  38.         //打開這個Notification通知    

  39.         mManager.notify(0, notification);    

  40.         }    

  41.     });    

  42.         

  43.     Button button1 = (Button)findViewById(R.id.button1);    

  44.     button1.setOnClickListener(new OnClickListener() {    

  45.             

  46.         @Override    

  47.         public void onClick(View arg0) {    

  48.         //關閉這個Notification通知    

  49.         mManager.cancelAll();    

  50.         }    

  51.     });    

  52.         

  53.     super.onCreate(savedInstanceState);    

  54.     }    

  55.     

  56. }    


3.廣播的發送與接收

Android開發中如果須要對兩個完全沒關係的程序之間進行通信 就可以使用發送廣播與接收廣播的機制來實現 ,例如程序A發送了一個廣播 程序B接受到 做一些事情 這樣就達到了相互的通訊。

[java] view plaincopy

  1. public class BroadcastActivity extends Activity {    

  2.     

  3.     

  4.        

  5.     Button mButton0 = null;    

  6.     Button mButton1 = null;    

  7.     

  8.     @Override    

  9.     protected void onCreate(Bundle savedInstanceState) {    

  10.     setContentView(R.layout.broadcast);    

  11.         

  12.     mButton0 = (Button)findViewById(R.id.button0);    

  13.     mButton0.setOnClickListener(new OnClickListener() {    

  14.             

  15.         @Override    

  16.         public void onClick(View arg0) {    

  17.                 Intent intent = new Intent(MyService.SEND_OK_MESSAGE);    

  18.                 intent.putExtra("name""您發送了OK這條廣播哦");    

  19.                 sendBroadcast(intent);    

  20.         }    

  21.     });    

  22.     

  23.     mButton1 = (Button)findViewById(R.id.button1);    

  24.     mButton1.setOnClickListener(new OnClickListener() {    

  25.             

  26.         @Override    

  27.         public void onClick(View arg0) {    

  28.                 Intent intent = new Intent(MyService.SEND_CANCLE_MESSAGE);    

  29.                 intent.putExtra("name""您發送了Cancle這條廣播哦");    

  30.                 sendBroadcast(intent);    

  31.         }    

  32.     });    

  33.         

  34.     //啓動Service     

  35.     Intent i = new Intent(this, MyService.class);    

  36.     startService(i);    

  37.     super.onCreate(savedInstanceState);    

  38.     }    

  39. }    


[java] view plaincopy

  1. 接收廣播的話 我們開啓一個service 在service中通過BroadcastReceiver 來接收廣播 前提是須要接收的廣播須要在onStart()中註冊一下 在AndroidManifest.xml中可以過濾只接收須要接收的廣播、  

  2.   

  3. view plain  

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

  5.     <intent-filter>    

  6.         <action android:name="cn.m15.xys.MyService"></action>    

  7.     </intent-filter>    

  8.     <intent-filter>    

  9.         <action android:name="send.ok.message" />    

  10.         <action android:name="send.cancle.message" />    

  11.     </intent-filter>    

  12. </service>    

  13.   

  14.   

  15. 在onStart()中註冊了程序中所需要的兩個廣播  

  16.   

  17. view plain  

  18. public class MyService extends Service {    

  19.     

  20.     public final static String SEND_OK_MESSAGE = "send.ok.message";    

  21.     public final static String SEND_CANCLE_MESSAGE = "send.cancle.message";    

  22.         

  23.     private BroadcastReceiver myBroadCast = new BroadcastReceiver() {    

  24.     

  25.     @Override    

  26.     public void onReceive(Context context, Intent intent) {    

  27.         String action = intent.getAction();    

  28.         if (action.equals(SEND_OK_MESSAGE)) {    

  29.         Toast.makeText(context, "接收到了一條廣播爲" + SEND_OK_MESSAGE, Toast.LENGTH_LONG).show();    

  30.         }else if(action.equals(SEND_CANCLE_MESSAGE)) {    

  31.         Toast.makeText(context, "接收到了一條廣播爲" + SEND_CANCLE_MESSAGE, Toast.LENGTH_LONG).show();    

  32.         }    

  33.     }    

  34.     

  35.     };    

  36.     

  37.     @Override    

  38.     public void onCreate() {    

  39.     super.onCreate();    

  40.     }    

  41.     

  42.     @Override    

  43.     public void onStart(Intent intent, int startId) {    

  44.     //註冊這兩個廣播    

  45.     IntentFilter myFilter = new IntentFilter();    

  46.     myFilter.addAction(SEND_OK_MESSAGE);    

  47.     myFilter.addAction(SEND_CANCLE_MESSAGE);    

  48.     this.registerReceiver(myBroadCast, myFilter);    

  49.         super.onStart(intent, startId);    

  50.     }    

  51.     @Override    

  52.     public IBinder onBind(Intent arg0) {    

  53.     return null;    

  54.     }    

  55.     

  56. }    

  57.   

  58.         這裏注意一下 service如果沒有起來 我們是接收不到廣播的 所以一定要保證接收的時候service是開啓的,上例中的service是在打開activity時開啓的 但是如果用戶把手機關掉然後在開機 , 這樣的話service就不是打開狀態 這樣就非常危險了因爲這時scrvice就接收不到任何消息了除非用戶再次進activity 纔會幫他打開scrvice 所以我們可以在用戶開機後就直接將scrvice打開,具體的實現方式如下  

  59.   

  60. 在AndroidManifest.xml中註冊一個開機廣播  這個廣播系統只會在開機發出而且只會發出一次 所以我們接收這個廣播就可以知道手機是否爲開機狀態  

  61.   

  62. view plain  

  63. <receiver android:name=".MyBootReceiver" >    

  64.       <intent-filter>    

  65.          <action android:name="android.intent.action.BOOT_COMPLETED" />    

  66.      </intent-filter>    

  67.    </receiver>    

  68.   

  69. 注意加入權限   

  70.   

  71. view plain  

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

  73.   

  74. 在BroadcastRecevier中接收開機廣播  然後打開service 就可以實現開機啓動service。  

  75.   

  76. view plain  

  77. public class MyBootReceiver extends BroadcastReceiver {    

  78.    /**開機廣播**/    

  79.     static final String BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";    

  80.     

  81.     @Override    

  82.     public void onReceive(Context context, Intent intent) {    

  83.     /**如果爲開機廣播則開啓service**/    

  84.     if (intent.getAction().equals(BOOT_COMPLETED)) {    

  85.         Intent i = new Intent(context, MyService.class);    

  86.         context.startService(i);    

  87.     }    

  88.     

  89.     }    

  90. }    


4.Activity與Activity之間的轉跳

在軟件應用的開發中肯定會有多個Activity     這樣它們之間就會存在相互轉跳的關係      轉跳的實現方式還是使用Intent  然後startActivity  ,當然轉跳的話是可以帶數據過去的。比如從A跳到B 可以把A中的一些數據通過Intent傳遞給B 。

[java] view plaincopy

  1. 讀下面這段代碼 大家會發現intent與bandle 傳遞數值的方式基本一樣爲什麼還要分成兩個呢? 確實他們兩個傳遞的數值的方式非常類似, 他們兩個的區別就是Intent屬於把零散的數據傳遞過去 而bundle則是把零散的數據先放入bundle 然後在傳遞過去。我舉一個例子 比如我們現在有3個activity  A.B.C  須要把A的數據穿給B然後在穿給C ,如果使用intent一個一個傳遞 須要在A類中一個一個傳遞給B 然後B類中獲取到所有數值  然後在一個一個傳遞給C  這樣很麻煩 但是 如果是bundle的話 B類中直接將bundler傳遞給C 不用一個一個獲得具體的值  然後在C類中直接取得解析數值。  

  2.   

  3. 傳遞  

  4. view plain  

  5.        /**Activity之間傳遞值**/    

  6.        Button botton3 = (Button)findViewById(R.id.button3);    

  7.        botton3.setOnClickListener(new OnClickListener() {    

  8.         

  9.     @Override    

  10.     public void onClick(View arg0) {    

  11.      Intent intent = new Intent(mContext,ShowActivity.class);     

  12.      //使用intent.putExtra()直接傳遞    

  13.      intent.putExtra("name""雨鬆MOMO");    

  14.      intent.putExtra("age"25);    

  15.      intent.putExtra("boy"true);    

  16.         

  17.      //把數值放進bundle 然後在把整個bundle通過intent.putExtra()傳遞    

  18.      Bundle bundle = new Bundle();    

  19.      bundle.putString("b_name""小可愛");    

  20.      bundle.putInt("b_age"23);    

  21.      bundle.putBoolean("b_boy"false);    

  22.      //在這裏把整個bundle 放進intent中    

  23.      intent.putExtras(bundle);    

  24.      //開啓一個新的 activity 將intent傳遞過去    

  25.      startActivity(intent);    

  26.     }    

  27. });       

  28.   

  29. 接收  

  30. view plain  

  31. public class ShowActivity extends Activity {    

  32.         

  33.     @Override    

  34.     protected void onCreate(Bundle savedInstanceState) {    

  35.     setContentView(R.layout.my);    

  36.         

  37.     Intent intent = getIntent();    

  38.         

  39.     String name = intent.getStringExtra("name");    

  40.     //第二個參數爲默認值 意思就是如果在intent中拿不到的話    

  41.     //就用默認值    

  42.     int age  = intent.getIntExtra("age"0);    

  43.     boolean isboy = intent.getBooleanExtra("boy"false);    

  44.     TextView textView0 = (TextView)findViewById(R.id.text0);    

  45.         

  46.     textView0.setText("姓名  " + name + "年齡 " + age + "男孩?  " + isboy);    

  47.         

  48.         

  49.     Bundle bundle = intent.getExtras();    

  50.     name = bundle.getString("b_name");    

  51.     //第二個參數爲默認值 意思就是如果在bundle中拿不到的話    

  52.     //就用默認值    

  53.     age = bundle.getInt("b_age",0);    

  54.     isboy = bundle.getBoolean("b_boy"false);    

  55.         

  56.     TextView textView1 = (TextView)findViewById(R.id.text1);    

  57.         

  58.     textView1.setText("姓名  " + name + "年齡 " + age + "男孩?  " + isboy);    

  59.         

  60.     super.onCreate(savedInstanceState);    

  61.     }    

  62.     

  63. }    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章