package com.example.service; 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.Toast; public class MainActivity extends Activity { MyBroadcast mybroadcast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void start(View view) { Intent intent = new Intent(MainActivity.this, MyService.class); intent.putExtra("number", 1); startService(intent); // 啟動(dòng)service } public void stop(View view) { stopService(new Intent(MainActivity.this, MyService.class)); } public class MyBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int count = intent.getIntExtra("count", 0); System.out.println("*****" + count + "******"); Toast.makeText(context, "當(dāng)前數(shù)字為:" + count, Toast.LENGTH_LONG).show(); // 顯示service發(fā)來得數(shù)據(jù) } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mybroadcast);// 取消注冊 } @Override protected void onStart() { super.onStart(); mybroadcast = new MyBroadcast(); IntentFilter filter = new IntentFilter(); filter.addAction("com.cwb.ServiceActivity"); registerReceiver(mybroadcast, filter); // 注冊Broadcast Receiver } } package com.example.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); } @Override public void onStart(Intent intent, int startId) { System.out.println("service啟動(dòng)成功?。。?); int mynumber = intent.getIntExtra("number", 3); for (int i = 10; mynumber < i; mynumber++) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Intent serviceIntent = new Intent(); serviceIntent.setAction("com.cwb.ServiceActivity"); serviceIntent.putExtra("count", mynumber); sendBroadcast(serviceIntent); // 每隔2秒發(fā)送一個(gè)廣播到ServiceActivity } } }
文章標(biāo)題:安卓Service的使用
網(wǎng)站地址:http://jinyejixie.com/article48/gdpcep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、建站公司、關(guān)鍵詞優(yōu)化、營銷型網(wǎng)站建設(shè)、做網(wǎng)站、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)