service

来源:互联网 发布:98老版水浒知寨夫人 编辑:程序博客网 时间:2024/05/29 10:55

这个例子来自“安卓巴士”,经阅读,理解,写此文章,希望通过这篇一个Demo学完Android中所有的服务对对广大读者有所帮助。

说明:这个例子实现了Android中常见的许多服务,下面是实现的截图

接下来,以源代码的方式分析这个例子

1.MainActivity--主界面

这个类主要是实现用户所看到的这个Activity,其中包含了一系列的按钮,用户点击按钮执行相应的动作,所以在这个类中主要是对按钮的定义和对按钮绑定相应的监听器,下面是实现的代码:

  1. package lovefang.stadyService;   
  2.    
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.widget.Button;   
  6. import android.view.View;   
  7. import android.content.Intent;   
  8. import android.util.Log;   
  9. /**这是使用后台服务的学习例子*/   
  10. public class MainStadyServics extends Activity {   
  11.         /**参数设置*/   
  12.     Button startServiceButton;// 启动服务按钮   
  13.     Button shutDownServiceButton;// 关闭服务按钮   
  14.     Button startBindServiceButton;// 启动绑定服务按钮   
  15.     Button sendBroadcast;// 使用广播   
  16.     Button notificationButton;// 使用通知功能   
  17.     Button alarmButton;// 使用闹钟   
  18.     Button handlerButton;// 使用handler   
  19.     Button asyncButton;// 使用异步加载   
  20.     Button phoneStateButton;// 查看手机状态   
  21.     Button callphoneButton;// 拨打电话   
  22.     Button vibratorButton;// 使用震动    
  23.     CountService countService;   
  24.        
  25.     @Override   
  26.     public void onCreate(Bundle savedInstanceState) {   
  27.         super.onCreate(savedInstanceState);   
  28.         Log.v("MainStadyServics""setContentView");   
  29.         setContentView(R.layout.main);   
  30.         getWidget();   
  31.         regiestListener();   
  32.     }   
  33.         /**获得组件*/   
  34.     public void getWidget(){   
  35.         startServiceButton = (Button)findViewById(R.id.startServerButton);   
  36.         startBindServiceButton = (Button)findViewById(R.id.startBindServerButton);   
  37.         shutDownServiceButton = (Button)findViewById(R.id.sutdownServerButton);   
  38.         sendBroadcast = (Button)findViewById(R.id.sendBroadcast);   
  39.         notificationButton = (Button)findViewById(R.id.notification);   
  40.         alarmButton = (Button)findViewById(R.id.alarm);   
  41.         handlerButton = (Button)findViewById(R.id.handler);   
  42.         asyncButton = (Button)findViewById(R.id.async);   
  43.         phoneStateButton = (Button) findViewById(R.id.phonestate);   
  44.         callphoneButton = (Button) findViewById(R.id.callphone);   
  45.         vibratorButton = (Button) findViewById(R.id.vibrator);   
  46.     }   
  47.         /**为按钮添加监听*/   
  48.     public void regiestListener(){   
  49.         startServiceButton.setOnClickListener(startService);   
  50.         shutDownServiceButton.setOnClickListener(shutdownService);   
  51.         startBindServiceButton.setOnClickListener(startBinderService);   
  52.         sendBroadcast.setOnClickListener(broadcastReceiver);   
  53.         notificationButton.setOnClickListener(notification);   
  54.         alarmButton.setOnClickListener(startAlarm);   
  55.         handlerButton.setOnClickListener(handler);   
  56.         asyncButton.setOnClickListener(async);   
  57.         phoneStateButton.setOnClickListener(phonestate);   
  58.         callphoneButton.setOnClickListener(callphoneEvent);   
  59.         vibratorButton.setOnClickListener(vibrator);   
  60.     }   
  61.         /**启动服务的事件监听*/   
  62.     public Button.OnClickListener startService = new Button.OnClickListener(){   
  63.         public void onClick(View view){   
  64.                 /**单击按钮时启动服务*/   
  65.             Intent intent = new Intent(MainStadyServics.this,CountService.class);   
  66.             startService(intent);   
  67.             Log.v("MainStadyServics""start Service");   
  68.         }   
  69.     };   
  70.         /**关闭服务*/   
  71.     public Button.OnClickListener shutdownService = new Button.OnClickListener(){   
  72.         public void onClick(View view){   
  73.                 /**单击按钮时启动服务*/   
  74.             Intent intent = new Intent(MainStadyServics.this,CountService.class);   
  75.                 /**退出Activity是,停止服务*/   
  76.             stopService(intent);   
  77.             Log.v("MainStadyServics""shutDown serveice");   
  78.         }   
  79.     };   
  80.         /**打开绑定服务的Activity*/   
  81.     public Button.OnClickListener startBinderService = new Button.OnClickListener(){   
  82.         public void onClick(View view){   
  83.                 /**单击按钮时启动服务*/   
  84.             Intent intent = new Intent(MainStadyServics.this,UseBrider.class);   
  85.             startActivity(intent);   
  86.             Log.v("MainStadyServics""start Binder Service");   
  87.         }   
  88.     };   
  89.         /**打开广播学习的按钮*/   
  90.     public Button.OnClickListener broadcastReceiver = new Button.OnClickListener(){   
  91.         public void onClick(View view){   
  92.             Intent intent = new Intent(MainStadyServics.this,UseBroadcast.class);   
  93.             startActivity(intent);   
  94.             Log.v("MainStadyServics","start broadcast");   
  95.         }   
  96.     };   
  97.         /**打开通知*/   
  98.     public Button.OnClickListener notification = new Button.OnClickListener(){   
  99.         public void onClick(View view){   
  100.             Intent intent = new Intent(MainStadyServics.this, UseNotification.class);   
  101.             startActivity(intent);   
  102.             Log.v("MainStadyService ","start Notification");   
  103.                
  104.         }   
  105.     };   
  106.         /**使用闹钟*/   
  107.     public Button.OnClickListener startAlarm = new Button.OnClickListener(){   
  108.         public void onClick(View view){   
  109.             Intent intent = new Intent(MainStadyServics.this, UseAlarmManager.class);   
  110.             startActivity(intent);   
  111.             Log.v("MainStadyService ","start alarm");   
  112.                
  113.         }   
  114.     };   
  115.     public Button.OnClickListener handler= new Button.OnClickListener(){   
  116.         public void onClick(View view){   
  117.             Intent intent = new Intent(MainStadyServics.this, UseHandleMessage.class);   
  118.             startActivity(intent);   
  119.             Log.v("MainStadyService ","start handle");   
  120.         }   
  121.     };   
  122.     public Button.OnClickListener async= new Button.OnClickListener(){   
  123.         public void onClick(View view){   
  124.             Intent intent = new Intent(MainStadyServics.this, UseAsyncTask.class);   
  125.             startActivity(intent);   
  126.             Log.v("MainStadyService ","start handle");   
  127.         }   
  128.     };   
  129.     public Button.OnClickListener phonestate= new Button.OnClickListener(){   
  130.         public void onClick(View view){   
  131.             Intent intent = new Intent(MainStadyServics.this, UsePhoneState.class);   
  132.             startActivity(intent);   
  133.             Log.v("MainStadyService ","start phonestate");   
  134.         }   
  135.     };   
  136.     public Button.OnClickListener callphoneEvent= new Button.OnClickListener(){   
  137.         public void onClick(View view){   
  138.             Intent intent = new Intent(MainStadyServics.this, UseActionCall.class);   
  139.             startActivity(intent);   
  140.             Log.v("MainStadyService ","start callphone");   
  141.         }   
  142.     };   
  143.     public Button.OnClickListener vibrator= new Button.OnClickListener(){   
  144.         public void onClick(View view){   
  145.             Intent intent = new Intent(MainStadyServics.this, UseVibrator.class);   
  146.             startActivity(intent);   
  147.             Log.v("MainStadyService ","start callphone");   
  148.         }   
  149.     };   
  150.         /***/   
  151.     protected void onDestroy(){   
  152.         super.onDestroy();   
  153.         Intent intent = new Intent(MainStadyServics.this,CountService.class);   
  154.             /**退出Activity是,停止服务*/   
  155.         stopService(intent);   
  156.     }   
  157.            
  158.        
  159. }   

2.启动服务按钮

这个类实现的是第一个按钮的功能,在这个类中新开了一个线程,并每隔一秒打印出一行日志

代码如下:

  1. package lovefang.stadyService;   
  2. /**引入包*/   
  3.     import android.app.Service;// 服务的类   
  4.     import android.os.IBinder;   
  5.     import android.os.Binder;   
  6.     import android.content.Intent;   
  7.     import android.util.Log;   
  8. /**计数的服务*/   
  9.     public class CountService extends Service{   
  10.             /**创建参数*/   
  11.         boolean threadDisable ;   
  12.         int count;   
  13.            
  14.         public IBinder onBind(Intent intent){   
  15.             return null;   
  16.         }   
  17.         public void onCreate(){   
  18.             super.onCreate();   
  19.                 /**创建一个线程,每秒计数器加一,并在控制台进行Log输出*/   
  20.             new Thread(new Runnable(){   
  21.                 public void run(){   
  22.                     while(!threadDisable){   
  23.                         try{   
  24.                             Thread.sleep(1000);   
  25.                         }catch(InterruptedException e){   
  26.                                
  27.                         }   
  28.                         count++;   
  29.                         Log.v("CountService","Count is"+count);   
  30.                     }   
  31.                 }   
  32.             }).start();   
  33.         }   
  34.         public void onDestroy(){   
  35.             super.onDestroy();   
  36.                 /**服务停止时,终止计数进程*/   
  37.             this.threadDisable = true;   
  38.         }   
  39.         public int getConunt(){   
  40.             return count;   
  41.         }   
  42.         class ServiceBinder extends Binder{   
  43.             public CountService getService(){   
  44.                 return CountService.this;   
  45.             }   
  46.         }   
  47.     }   

3.绑定服务

服务有两种实现的方法:

(1)startService,启动服务,这时需要程序员管理服务的生命周期

(2)bindService,绑定服务,此时Service与Activity绑定在一起

下面是实现的代码:

  1. package lovefang.stadyService;   
  2. /**引入包*/   
  3.     import android.app.Activity;   
  4.     import android.content.ComponentName;   
  5.     import android.content.Context;   
  6.     import android.content.Intent;   
  7.     import android.content.ServiceConnection;   
  8.     import android.os.Bundle;   
  9.     import android.os.IBinder;   
  10.     import android.util.Log;   
  11.    
  12. /**通过bindService和unBindSerivce的方式启动和结束服务*/   
  13.     public class UseBrider extends Activity {   
  14.             /**参数设置*/   
  15.         CountService countService;   
  16.        
  17.         @Override   
  18.         public void onCreate(Bundle savedInstanceState) {   
  19.             super.onCreate(savedInstanceState);   
  20.             setContentView(new UseBriderFace(this));   
  21.             Intent intent = new Intent(UseBrider.this,CountService.class);   
  22.                 /**进入Activity开始服务*/   
  23.             bindService(intent, conn, Context.BIND_AUTO_CREATE);   
  24.                
  25.         }   
  26.         private ServiceConnection conn = new ServiceConnection(){   
  27.                 /**获取服务对象时的操作*/    
  28.             public void onServiceConnected(ComponentName name, IBinder service) {   
  29.                 // TODO Auto-generated method stub   
  30.                 countService = ((CountService.ServiceBinder)service).getService();   
  31.                    
  32.             }   
  33.                 /**无法获取到服务对象时的操作*/   
  34.             public void onServiceDisconnected(ComponentName name) {   
  35.                 // TODO Auto-generated method stub   
  36.                 countService =null;   
  37.             }   
  38.                
  39.                
  40.         };   
  41.         protected void onDestroy(){   
  42.             super.onDestroy();   
  43.             this.unbindService(conn);   
  44.             Log.v("MainStadyServics""out");   
  45.         }   
  46.     }   

接下来为您介绍发送广播、Notification通知、Alarm 闹钟等服务的具体内容

原创粉丝点击