您好,登錄后才能下訂單哦!
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); // 啟動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啟動成功!!!"); 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ā)送一個廣播到ServiceActivity } } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。