Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1736451
  • 博文数量: 438
  • 博客积分: 9799
  • 博客等级: 中将
  • 技术积分: 6092
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 17:25
文章分类

全部博文(438)

文章存档

2019年(1)

2013年(8)

2012年(429)

分类: 嵌入式

2012-03-25 21:15:17

从Service类继承一个子类:
  1. package tommy.myandroid;

  2. import android.app.IntentService;
  3. import android.content.Intent;

  4. public class UglyService extends IntentService {
  5.     public UglyService(String name) {
  6.         super(name);
  7.     }

  8.     @Override
  9.     public void onHandleIntent(Intent intent) {
  10.         for (int i = 0; i < 10; ++i) {
  11.             // do something
  12.         }
  13.     }
  14. }

IntentService是Service的子类,在服务开始后,它会新建一个worker线程,这个线程会调用onHandleIntent方法。如果你直接从Service继承,可以override它的OnStartCommand方法,在此方法中开一个线程达到同样的效果。
记得在manifest里注册该service:
  1. <service android:name=".UglyService" android:label="Ugly Service">
  2.             <intent-filter>
  3.                 <action android:name="anyone.anything.ugly" />
  4.                 <category android:name="android.intent.category.DEFAULT" />
  5.             </intent-filter>
  6.         </service>

这样一个新的Service就建好了。只要调用startService(Intent)方法就能开始一个service了。

broadcast receiver也类似:


  1. package tommy.myandroid;

  2. import android.app.Notification;
  3. import android.app.NotificationManager;
  4. import android.app.PendingIntent;
  5. import android.content.BroadcastReceiver;
  6. import android.content.Context;
  7. import android.content.Intent;

  8. public class HappyReceiver extends BroadcastReceiver {
  9.     static int id;
  10.     @Override
  11.     public void onReceive(Context context, Intent intent) {
  12.         NotificationManager nm =
  13.                 (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  14.         Notification n = new Notification(R.drawable.icon, "Notice!!", System.currentTimeMillis());
  15.         n.setLatestEventInfo(context, "Title", "Content text",
  16.                 PendingIntent.getActivity(context, 0, new Intent("anyone.anything.beauty"), 0));
  17.         nm.notify(id++, n);
  18.     }
  19. }

manifest:
  1. <receiver android:name=".HappyReceiver" android:label="Happy Receiver">
  2.             <intent-filter>
  3.                 <action android:name="anyone.anything.happy" />
  4.                 <category android:name="android.intent.category.DEFAULT" />
  5.             </intent-filter>
  6.         </receiver>

NotificationManager用来发送一个通知,比如新短信消息。Notification对象包含了一些有用的信息比如消息内容和消息时间。注意到这样一行语句:PendingIntent.getActivity(.....),它返回一个(Action为“beauty”的)PendingIntent实例,它的作用是用户查看消息详情时可以通过这个PendingIntent来启动相应的activity(BeautyActivity)。为什么要PendingIntent而不是直接使用Intent?因为创建创建Intent的程序退出后,它所拥有的Intent也会失效。由于执行这个activity的时间并不确定,为防止Intent失效,所以使用PendingIntent。
阅读(1250) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~