ServiceActivity代码:
package com.cwb;
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.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ServiceActivity extends Activity{
private Button button;
MyBroadcast mybroadcast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service);
button = (Button)findViewById(R.id.service);
button.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(ServiceActivity.this,com.cwb.MyService.class);
intent.putExtra("number", 1);
ServiceActivity.this.startService(intent); //启动service
}
});
}
@Override
protected void onStart() {
mybroadcast = new MyBroadcast();
IntentFilter filter = new IntentFilter();
filter.addAction("com.cwb.ServiceActivity");
registerReceiver(mybroadcast, filter); //注册Broadcast Receiver
super.onStart();
}
@Override
protected void onStop() {
unregisterReceiver(mybroadcast);//取消注册
super.onStop();
}
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发来得数据
}
}
}
MyService代码:
package com.cwb;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class MyService extends Service{
myReceiver myreceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
myreceiver = new myReceiver(); //创建BroadcastReceiver子类对象
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
System.out.println("service启动成功!!!");
IntentFilter filter = new IntentFilter();
filter.addAction("com.cwb.MyService");
registerReceiver(myreceiver, filter);
//注册Broadcast Receiver,若service不需要接受activity发来的广播也可以不写
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
}
}
@Override
public void onDestroy() {
unregisterReceiver(myreceiver); //取消注册
super.onDestroy();
}
private class myReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//这里接受处理activity传来的广播,如手动控制service停止等
}
}
}
运行效果:
当点击了GO按钮之后,会弹出“当前数字为:1至9”
好了,就到这里,欢迎大家交流。