應用程式間的通訊

來源:互聯網
上載者:User

主類:

1.啟動Service:

Intent startIntent = new Intent(主類.this, Service類.class);

startService(startIntent);

 

2.停止Service(發送廣播資訊給Service):

Intent stopIntent = new Intent();

stopIntent.setAction("Service類");

stopIntent.puExtra("cmd", 0);

sendBroadcast(stopIntent);

 

3.編寫內部類,用於接收Service服務的訊息:

private class DataReceiver extends BroadcastReceiver

{

@Override

public void onReceive(Context context, Intent intent)

{

double data = intent.getDoubleExtra("data", 0);

}

}

 

4.重寫onStart和onStop方法,添加註冊和取消註冊BroadcastReceicver:

protected void onStart()

{

dataReceiver = new DataReceiver();

IntentFilter filter = new IntentFilter();

filter.addAction("主類");

registerReceiver(dataReceiver, filter); /* Service服務發送訊息時也會設定"主類"這個過濾條件,兩邊的過濾條件一致,發送的訊息才能被正確接收 */

super.onStart();

}

 

protected void onStop()

{

unregisterReceiver(dataReceiver);

super.onStop();

}

 

Service類:

1.Service子類需要繼續Service類

2.建立內部類,用於接收主類發來的訊息(用於停止後台Service服務):

private class CommandReceiver extends BroadcastReceiver

{

@Override

public void onReceiver(Context context, Intent intent)

{

/* 主類要停止Service服務的時候,會發送一個廣播訊息給Service服務,值為0 */

int cmd = intent.getIntExtra("cmd", -1);

if(cmd == 0)

{

stopSelf();

}

}

}

 

3.重寫onBind方法(這步沒弄懂):

public IBinder onBind(Intent intent)

{

retun null;

}

 

4.重寫onStartCommand方法(應該是2.1之後的SDK才加進去的方法):

public void onStartCommand(Intent intent, int flags, int startId)

{

/* 此處註冊的cmdReveicer,用於接收主類發送過來的廣播訊息(用於停止Service服務),主類和Service類的過濾條件(“Service類”)必須相同 */

IntentFilter filter = new IntentFilter();

filter.addAction("Service類");

registerReceiver(cmdReveicer, filter); /*  cmdReveicer為CommandReceiver 對象 ,在onCreate的時候建立*/

 

/* 發送廣播訊息給主類,同樣,主類和Service類的過濾條件(“Service類”)必須相同 */

Intent intent = new Intent();

intent.setAction("主類");

intent.putExtra("data", 777);  /* 發送數字777給主類 */

sendBroadcast(intent);

 

return super.onStartCommand(ntent, flags, startId);

}

 

5.重寫onDestroy方法,在該方法中取消註冊cmdReveicer

 

6.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.