zoukankan      html  css  js  c++  java
  • Android 程式开发:(廿二)服务 —— 22.1 自定义服务

    服务,就是跑在后台的“程序”,不需要和用户进行交互。举个例子,当使用一款应用的时候,可能同时想在后台播放一些音乐。在这种情况下,后来播放音乐的代码不需要和用户进行交互,所以,它就可能被当成一个服务。当不需要给用户提供UI的时候,服务也是一种非常好的选择。

    想要彻底的了解服务的工作原理,最好的办法就是去着手尝试一下。下面将会新建一个简单的服务,并且在其中添加一些方法。讲述如何开启和关闭一个服务。

    1. 新建一个工程,Services。

    2. 新建一个类,MyService。

    public class MyService extends Service {
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    		return START_STICKY;
        }
    	
    
    	@Override
    	public void onDestroy() {
    		super.onDestroy();
    		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    	}
    }


    3. 修改AndroidManifest.xml。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="net.manoel.Services"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="14" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:label="@string/app_name"
                android:name=".ServicesActivity" >
                <intent-filter >
                    <action android:name="android.intent.action.MAIN" />                           
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            
            <service android:name=".MyService">
                <intent-filter>
                    <action android:name="net.manoel.MyService" />
                </intent-filter>
            </service>        
        </application>
    
    </manifest>


    4. 修改main.xml。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
    <Button android:id="@+id/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" 
        android:onClick="startService"/>
    
    <Button android:id="@+id/btnStopService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:onClick="stopService" />
        
    </LinearLayout>


    5. 修改ServicesActivity.java。

    public class ServicesActivity extends Activity {
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
        
        public void startService(View view) {
            startService(new Intent(getBaseContext(), MyService.class));
        }
        
        public void stopService(View view) {
            stopService(new Intent(getBaseContext(), MyService.class));
        }
    
    }

    6. 调试

    这个例子展示了最简单的服务。这个服务本身不会做什么有用的东西,只是显示服务创建的过程。

    首先,定义一个Serivce基类的子类。所有的服务都继承Service基类。

    public class MyService extends Service {
    
    }

    然后,实现3个方法。

        @Override
        public IBinder onBind(Intent arg0) { ... }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) { ... }
    	
    	@Override
    	public void onDestroy() { ... }


    onBind()方法可以把一个activity绑定到一个service上面。这就是说,这个方法可以让一个activity去直接访问一个service里面的成员变量和方法。目前,仅仅返回一个null,后续再讨论这个方法。

    onStartCommand()方法,在调用startService()的时候被调用。这个方法意味着service的开始,这里可以写一些自己的代码逻辑。这里,我返回了一个常量START_STICKY,这样的话,如果这个service不stop的话就会一直跑下去。

    onDestroy()方法,在调用stopService()的时候被调用。这里可以清理service用到过的资源。

    除了代码中的例子,也可以用另外一种方法去开启服务。

    在AndroidManifest.xml中声明Action。

            <service android:name=".MyService">
                <intent-filter>
                    <action android:name="net.manoel.MyService" />
                </intent-filter>
            </service>        
    startService(new Intent("net.manoel.MyService"));


    想要停止一个服务,调用stopService():

    stopService(new Intent(getBaseContext(), MyService.class));


  • 相关阅读:
    《人件》阅读笔记五
    《人件》阅读笔记四
    《人件》阅读笔记三
    《人件》阅读笔记二
    《人件》阅读笔记一
    年报系统课堂讨论记录
    系统利益相关者描述案例
    Android开发学习记录--活动生命周期
    jQuery AJAX简介
    jQuery HTML简介
  • 原文地址:https://www.cnblogs.com/james1207/p/3299406.html
Copyright © 2011-2022 走看看