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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。