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
}
}
}
标题名称:安卓Service的使用
分享网址:
http://cdweb.net/article/gdpcep.html