前台Service

MainActivity如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package cc.testservice2;  
  2. import android.app.Activity;  
  3. import android.content.ComponentName;  
  4. import android.content.Intent;  
  5. import android.content.ServiceConnection;  
  6. import android.os.Bundle;  
  7. import android.os.IBinder;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.TextView;  
  12. /** 
  13.  * Demo描述: 
  14.  * 前台Service使用示例 
  15.  *  
  16.  *  
  17.  * 主要实现: 
  18.  * 1 在Service的onCreate()中调用startForeground() 
  19.  * 2 在Service的onDestroy()中调用stopForeground() 
  20.  * 3 一个Notification常驻在状态栏,当后台数据变化时需要 
  21.  *   更新该通知中的显示内容.在该示例中只用了一个简单的 
  22.  *   系统自带Notification来演示,实际项目中多半会用到 
  23.  *   自定义的Notification涉及到RemoteView. 
  24.  *  
  25.  *  
  26.  * 前台服务的特点: 
  27.  * 1 可尽量避免系统内容不足的时候被系统回收 
  28.  * 2 它会有一个图标一直在状态栏显示,拉下状态栏后可见更多信息. 
  29.  *   比如有的天气App就采用了该前台服务来实现. 
  30.  *    
  31.  *    
  32.  * 测试环境: 
  33.  * 1 该示例测试环境为Android4.4 
  34.  * 2 在Android2.3及其以下版本可能报错: 
  35.  *   java.lang.IllegalArgumentException: contentIntent required 
  36.  *    
  37.  *  
  38.  * 注意权限: 
  39.  *  <uses-permission android:name="android.permission.VIBRATE"/> 
  40.  *   
  41.  *  
  42.  * 参考资料: 
  43.  * 1 http://blog.csdn.net/guolin_blog/article/details/11952435 
  44.  * 2 http://blog.csdn.net/lfdfhl/article/details/38226523 
  45.  * 3 http://blog.csdn.net/vipzjyno1/article/details/25248021 
  46.  * 4 http://blog.csdn.net/think_soft/article/details/7299438 
  47.  * 5 http://blog.csdn.net/lfdfhl/article/details/10044161 
  48.  *   Thank you very much 
  49.  */  
  50. public class MainActivity extends Activity {  
  51.     TextView mNumberTextView;  
  52.     TextView mResultTextView;  
  53.     Button mSearchButton;    
  54.     ServiceConnectionImpl mServiceConnectionImpl;  
  55.     QueryInterface  mBinder;   
  56.     public void onCreate(Bundle savedInstanceState) {  
  57.         super.onCreate(savedInstanceState);  
  58.         setContentView(R.layout.main);  
  59.         //用于接收服务返回的Binder对象  
  60.         mServiceConnectionImpl=new ServiceConnectionImpl();  
  61.         mNumberTextView=(TextView) findViewById(R.id.numberEditText);  
  62.         mResultTextView=(TextView) findViewById(R.id.resultTextView);  
  63.         mSearchButton=(Button) findViewById(R.id.searchButton);  
  64.         mSearchButton.setOnClickListener(new ButtonOnClickListener());  
  65.         Intent intent=new Intent(this,ServiceSubclass.class);  
  66.         //当Activity启动的时候就启动服务  
  67.         bindService(intent, mServiceConnectionImpl, this.BIND_AUTO_CREATE);  
  68.     }  
  69.       
  70.     private class ButtonOnClickListener implements OnClickListener{  
  71.         public void onClick(View v) {             
  72.             String number=mNumberTextView.getText().toString();  
  73.             String result=mBinder.queryByNumber(Integer.valueOf(number));  
  74.             mResultTextView.setText(result);  
  75.         }         
  76.     }  
  77.       
  78.     //绑定服务和解除服务  
  79.     private final class ServiceConnectionImpl implements ServiceConnection{  
  80.         //绑定服务时,此方法调用  
  81.         public void onServiceConnected(ComponentName name, IBinder service) {  
  82.              mBinder=(QueryInterface) service;            
  83.         }  
  84.         //解除服务时,此方法调用  
  85.         public void onServiceDisconnected(ComponentName name) {  
  86.             mBinder=null;  
  87.         }         
  88.     }  
  89.       
  90.    //解除与服务的连接  
  91.     protected void onDestroy() {  
  92.         unbindService(mServiceConnectionImpl);  
  93.         super.onDestroy();    
  94.     }  
  95.      
  96.       
  97. }  



ServiceSubclass如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package cc.testservice2;  
  2.   
  3. import android.app.Notification;  
  4. import android.app.Notification.Builder;  
  5. import android.app.NotificationManager;  
  6. import android.app.PendingIntent;  
  7. import android.app.Service;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.os.Binder;  
  11. import android.os.IBinder;  
  12.   
  13. public class ServiceSubclass extends Service {  
  14.     private String[] names = new String[] { "小明""小王""小杨""小李""小强" };  
  15.     BinderSubclass mBinderSubclass = new BinderSubclass();  
  16.     private String result=null;  
  17.     private Context mContext;  
  18.     private Builder mBuilder;  
  19.     private PendingIntent mPendingIntent;  
  20.     private Notification mNotification;  
  21.     private NotificationManager mNotificationManager;  
  22.     private final int NOTIFICATION_ID=9527;  
  23.     @Override  
  24.     public void onCreate() {  
  25.         super.onCreate();  
  26.         mContext=this;  
  27.         System.out.println("在onCreate()中---> startForeground()");  
  28.         //准备Notification  
  29.         initNotification(mContext);  
  30.         //开启前台服务  
  31.         startForeground(NOTIFICATION_ID, mNotification);  
  32.     }  
  33.       
  34.       
  35.     @Override  
  36.     public IBinder onBind(Intent intent) {  
  37.         return mBinderSubclass;  
  38.     }  
  39.       
  40.     @Override  
  41.     public void onDestroy() {  
  42.         super.onDestroy();  
  43.         //终止前台服务  
  44.         stopForeground(true);  
  45.         System.out.println("在onDestroy()中---> stopForeground()");  
  46.     }  
  47.       
  48.       
  49.       
  50.     // queryByNumber就是接口里的业务方法.  
  51.     //一般来讲将业务抽象为一个接口,然后去实现接口,比如此处。  
  52.     // 注意:BinderSubclass继承自Binder也实现了业务接口  
  53.     private final class BinderSubclass extends Binder implements QueryInterface {  
  54.         public String queryByNumber(int number) {  
  55.             return query(number);  
  56.         }  
  57.     }  
  58.   
  59.     //服务内部的方法  
  60.     public String query(int i) {  
  61.         if (i > 0 && i < 6) {  
  62.             result=names[i - 1];  
  63.             //更新通知  
  64.             updateNotification(result);  
  65.             return result;  
  66.         }  
  67.         return "查询错误,请再次输入";  
  68.     }  
  69.   
  70.     /** 
  71.      * 发送通知 
  72.      */  
  73.     private void initNotification(Context context){  
  74.         Intent intent=new Intent(mContext, MainActivity.class);  
  75.         mPendingIntent=PendingIntent.getActivity(mContext, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT);  
  76.         mNotificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);  
  77.         mBuilder=new Builder(mContext);  
  78.         //通知产生的时间  
  79.         mBuilder.setWhen(System.currentTimeMillis());  
  80.         //通知首次出现在通知栏时的提示文字  
  81.         mBuilder.setTicker("Ticker");  
  82.         mBuilder.setContentTitle("ContentTitle");  
  83.         mBuilder.setContentInfo("ContentInfo");  
  84.         mBuilder.setContentText("ContentText");  
  85.         mBuilder.setContentIntent(mPendingIntent);  
  86.         //通知的优先级  
  87.         mBuilder.setPriority(Notification.PRIORITY_DEFAULT);  
  88.         //设置通知的图标.必须要有这句否则通知不显示!!!  
  89.         mBuilder.setSmallIcon(R.drawable.ic_launcher);  
  90.         //为通知添加声音,闪灯和振动效果等效果  
  91.         mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);  
  92.         //设置通知是否为一个正在进行的通知.后台任务时常使用true  
  93.         mBuilder.setOngoing(false);  
  94.           
  95.         mNotification=mBuilder.build();  
  96.         //通知被点击后自动消失  
  97.         mNotification.flags = Notification.FLAG_AUTO_CANCEL;  
  98.         mNotificationManager.notify(NOTIFICATION_ID, mNotification);  
  99.     }  
  100.       
  101.       
  102.     /** 
  103.      * 更新通知 
  104.      */  
  105.     private void updateNotification(String result){  
  106.         mBuilder.setContentTitle("Title");  
  107.         mBuilder.setContentInfo("Info");  
  108.         mBuilder.setContentText(result);  
  109.         mNotification=mBuilder.build();  
  110.         mNotification.flags = Notification.FLAG_AUTO_CANCEL;  
  111.         mNotificationManager.notify(NOTIFICATION_ID, mNotification);  
  112.     }  
  113.   
  114. }  



QueryInterface如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package cc.testservice2;  
  2. //业务接口  
  3. public interface QueryInterface {  
  4.    public String queryByNumber(int number);  
  5. }  

main.xml如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="请输入1到5的数字" />  
  11.   
  12.     <EditText  
  13.         android:id="@+id/numberEditText"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content" />  
  16.   
  17.     <Button  
  18.         android:id="@+id/searchButton"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="查询" />  
  22.   
  23.     <TextView  
  24.         android:id="@+id/resultTextView"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content" />  
  27.   
  28. </LinearLayout>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值