创建服务

作者:追风剑情 发布于:2015-7-23 21:10 分类:Android

一、创建MyService

  1. package com.example.androidtest;
  2.  
  3. import android.app.Service;
  4. import android.content.Intent;
  5. import android.os.IBinder;
  6. import android.widget.Toast;
  7.  
  8. public class MyService extends Service {
  9.  
  10. @Override
  11. public IBinder onBind(Intent intent) {
  12. // TODO Auto-generated method stub
  13. return null;
  14. }
  15. @Override
  16. public int onStartCommand(Intent intent, int flags, int startId){
  17. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
  18. //START_STICKY: 只要服务不被显式地停止,它都将继续运行。
  19. return START_STICKY;
  20. }
  21.  
  22. @Override
  23. public void onDestroy(){
  24. super.onDestroy();
  25. Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  26. }
  27. }

二、创建ServicesActivity

视图

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical"
  6. tools:context="${relativePackage}.${activityClass}" >
  7.  
  8.  
  9. <Button android:id="@+id/btnStartService"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. android:text="Start Service"
  13. android:onClick="startService" />
  14. <Button android:id="@+id/btnStopService"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:text="Stop Service"
  18. android:onClick="stopService" />
  19.  
  20. </LinearLayout>

代码

  1. package com.example.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.Menu;
  7. import android.view.MenuItem;
  8. import android.view.View;
  9.  
  10. public class ServicesActivity extends Activity {
  11.  
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_services);
  16. }
  17. public void startService(View view){
  18. startService(new Intent(getBaseContext(), MyService.class));
  19. //或者通过意图筛选器名称启动
  20. //startService(new Intent("com.example.androidtest.MyService"));
  21. }
  22. public void stopService(View view){
  23. stopService(new Intent(getBaseContext(), MyService.class));
  24. }
  25. }

三、配置AndroidManifest.xml

  1. <service android:name=".MyService">
  2. <intent-filter>
  3. <action android:name="com.example.androidtest.MyService" />
  4. </intent-filter>
  5. </service>

运行效果

sssssssss.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号