1.如题
主要实现
1.启动service,关闭service;
2.activity 向service发送广播。
3.service向 activity发送广播。
4.service 利用AliarmMnager定时向activity push 数据,其实也是发了个广播。
5.service 利用AliarmMnager周期性的向 activity push 数据,其实也是发了个广播
6.定时/周期性向通知栏推送消息
1.Demo.java
package aliusa.cn;
import android.app.Activity;
/**
* The Class Demo.
* @author aliusa
*/
public class Demo extends Activity{
TextView textView;
Button[] btn;
MyReceiver receiver = new MyReceiver();
static final String ACTION = "aliusa.cn.Demo";
String serviceState = "MyService is not Running.";
String requireData = "The data is";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.CENTER);
textView = new TextView(this);
textView.setText(serviceState + requireData);
layout.addView(textView);
btn = new Button[6];
btn[0] = new Button(this);
btn[1] = new Button(this);
btn[2] = new Button(this);
btn[3] = new Button(this);
btn[4] = new Button(this);
btn[5] = new Button(this);
btn[0].setText("StopService");
btn[1].setText("BackGround");
btn[2].setText("RequireData");
btn[3].setText("StartService");
btn[4].setText("RequireDataDelay 5s");
btn[5].setText("RequireDataRepeating 5s");
//1.activity communicate with service through broadcast
btn[0].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService();
}
});
btn[1].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//2.activity communicate with service through service instance.
btn[2].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyService.getInstance().pushDataImmediately();
}
});
btn[3].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService();
}
});
btn[4].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyService.getInstance().pushDataDelay();
}
});
btn[5].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyService.getInstance().pushDataRepeating();
}
});
layout.addView(btn[0]);
layout.addView(btn[1]);
layout.addView(btn[2]);
layout.addView(btn[3]);
layout.addView(btn[4]);
layout.addView(btn[5]);
setContentView(layout);
startService();
}
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
textView.setText(serviceState + requireData);
super.handleMessage(msg);
}
};
public void startService(){
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
registerReceiver(receiver, filter);
Intent i = new Intent(this, MyService.class);
startService(i);
serviceState = "MyService is Running.";
myHandler.sendEmptyMessage(0);
}
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
myHandler = null;
super.onDestroy();
}
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int data = bundle.getInt("data");
requireData = "The data is "+data;
myHandler.sendEmptyMessage(0);
}
}
public void stopService(){
Intent intent = new Intent();
intent.setAction(MyService.ACTION);
intent.putExtra("cmd", MyService.SERVICE_STOP);
sendBroadcast(intent);
serviceState = "MyService is not Running.";
myHandler.sendEmptyMessage(0);
}
}
2.MyService.java
package aliusa.cn;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.SystemClock;
import java.util.Calendar;
import java.util.Random;
/**
* The Class MyService.
* @author aliusa
*/
public class MyService extends Service{
static final int SERVICE_STOP = 0;
static final int SERVICE_PUSH_DATA = 1;
static final String ACTION= "aliusa.cn.MyService";
static MyService instance = null;
MyReceiver recevier;
NotificationManager nm;
AlarmManager am;
PendingIntent senderDelay;
PendingIntent senderRepeating;
public void registerReviver(){
recevier = new MyReceiver();
IntentFilter filter1 = new IntentFilter();
filter1.addAction(ACTION);
registerReceiver(recevier, filter1);
}
class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
int cmd = intent.getIntExtra("cmd", -1);
switch (cmd) {
case MyService.SERVICE_STOP:
stopSelf();
break;
case MyService.SERVICE_PUSH_DATA:
pushDataImmediately();
break;
}
}
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
registerReviver();
super.onStart(intent, startId);
}
/**
* Push data.
*/
public void pushData(){
final Random random = new Random();
Intent i = new Intent();
i.setAction(Demo.ACTION);
i.putExtra("data", random.nextInt(100));
sendBroadcast(i);
}
public void pushDataImmediately(){
showNotification();
pushData();
}
private void showNotification() {
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Demo.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
Notification myNotification = new Notification();
myNotification.icon = R.drawable.icon;
myNotification.defaults = Notification.DEFAULT_ALL;
myNotification.setLatestEventInfo(this, "MyService is running", "chose to have a look", pi);
nm.notify(0, myNotification);
}
@Override
public void onDestroy() {
cancelAlarmManager();
if (nm != null){
nm.cancelAll();
}
unregisterReceiver(recevier);
System.out.println("MyService.onDestroy");
super.onDestroy();
}
public void pushDataDelay() {
Intent intent = new Intent();
intent.setAction(MyService.ACTION);
intent.putExtra("cmd", MyService.SERVICE_PUSH_DATA);
senderDelay = PendingIntent.getBroadcast(this, 0, intent, 0);
//设定一个五秒后的时间
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
am =(AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), senderDelay);
//或者以下面方式简化
//alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, senderDelay);
}
/**
* Require data.
*/
public void pushDataRepeating() {
Intent intent = new Intent();
intent.setAction(MyService.ACTION);
intent.putExtra("cmd", MyService.SERVICE_PUSH_DATA);
senderRepeating = PendingIntent.getBroadcast(this, 1, intent, 0);
//开始时间
long firstime=SystemClock.elapsedRealtime();
am=(AlarmManager)getSystemService(ALARM_SERVICE);
//5秒一个周期,不停的发送广播
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5*1000, senderRepeating);
}
public void cancelAlarmManager(){
if (am != null) {
if (senderDelay != null) {
am.cancel(senderDelay);
senderDelay = null;
}
if (senderRepeating != null) {
am.cancel(senderRepeating);
senderRepeating = null;
}
am = null;
}
}
public static MyService getInstance() {
return instance;
}
}
3.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="aliusa.cn"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".Demo"
android:label="@string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="aliusa.cn.MyService">
</service>
</application>
<uses-sdk
android:minSdkVersion="7" />
</manifest>