http://blog.sina.com.cn/s/blog_70677d110100yaht.html
activity类:
package yt.hy.activity;
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.Button;
import android.widget.Toast;
public class ServiceActivityConnectionActivity extends Activity {
private Button button;
MyBroadcast mybroadcast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(ServiceActivityConnectionActivity.this, MyService.class);
intent.putExtra("number", 1);
// 给service发送参数
ServiceActivityConnectionActivity.this.startService(intent);
}
});
}
protected void onStart() {
mybroadcast = new MyBroadcast();
IntentFilter filter = new IntentFilter();
filter.addAction("yt.hy.activity.ServiceActivityConnectionActivity");
//注册一个接收
yt.hy.activity.ServiceActivityConnectionActivity的广播
registerReceiver(mybroadcast, filter);
super.onStart();
}
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);
Toast.makeText(context, "当前数字为:"+count, Toast.LENGTH_LONG).show();
}
}
}
service类:
package yt.hy.activity;
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();
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
IntentFilter filter = new IntentFilter();
filter.addAction("yt.hy.activity.MyService");
registerReceiver(myreceiver, filter);
int myNumber = intent.getIntExtra("number", 3);
for (int i=10; myNumber
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent serviceIntent = new Intent();
serviceIntent.setAction("yt.hy.activity.ServiceActivityConnectionActivity");
serviceIntent.putExtra("count", myNumber);
sendBroadcast(serviceIntent);
super.onStart(intent, startId);
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
private class myReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
}