您好,登錄后才能下訂單哦!
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, "當前數字為:" + count, Toast.LENGTH_LONG).show(); // 顯示service發來得數據 } } @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秒發送一個廣播到ServiceActivity } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。