用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - android代码库

Service Demo

2016-10-20 作者: 永夜极光举报

[android]代码库

1.在Manifest中注册 Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.acer.anew">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- 注册Service -->
        <service android:name="LocalService">
            <intent-filter>
                <action android:name="com.example.acer.ariew.LocalService" />
            </intent-filter>
        </service>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


2.LocalService.java

package com.example.acer.anew;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class LocalService extends Service {
    private static final String TAG = "MyService";
    private final IBinder myBinder = new LocalBinder();
    boolean threadDisable;
    int count;

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind()");

        return myBinder;
    }

    // 调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法
    @Override
    public void onCreate() {

    }

    // 调用startService方法启动Service时调用该方法
    @Override
    public void onStart(Intent intent, int startId) {
        new Thread(
                new Runnable() {
                    public void run() {
                        while (!threadDisable) {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                            }
                            count++;
                            Log.e(TAG, "Count is" + count);
                        }
                    }
                }).start();
    }


    // Service创建并启动后在调用stopService方法或unbindService方法时调用该方法
    public void onDestroy() {
            this.threadDisable = true;
    }
    //提供给客户端访问
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }
}

3.MainActivity.java

package com.example.acer.anew;
    import android.app.Service;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {
        private Button startBtn;
        private Button stopBtn;
        private Button bindBtn;
        private Button unBindBtn;
        private static final String TAG = "MainActivity";
        private LocalService myService;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            startBtn = (Button) findViewById(R.id.start);
            stopBtn = (Button) findViewById(R.id.stop);
            bindBtn = (Button) findViewById(R.id.bind);
            unBindBtn = (Button) findViewById(R.id.unbind);
            startBtn.setOnClickListener(new MyOnClickListener());
            stopBtn.setOnClickListener(new MyOnClickListener());
            bindBtn.setOnClickListener(new MyOnClickListener());
            unBindBtn.setOnClickListener(new MyOnClickListener());
        }

        class MyOnClickListener implements OnClickListener {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, LocalService.class);
                switch (v.getId()) {
                    case R.id.start:
                        // 启动Service
                        startService(intent);
                        toast("startService");
                        break;
                    case R.id.stop:
                        // 停止Service
                        stopService(intent);
                        toast("stopService");
                        break;
                    case R.id.bind:
                        // 绑定Service
                        bindService(intent, conn, Service.BIND_AUTO_CREATE);
                        toast("bindService");
                        break;
                    case R.id.unbind:
                        // 解除Service
                        unbindService(conn);
                        toast("unbindService");
                        break;
                }
            }
        }


        private void toast(final String tip){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
                }
            });
        }
        private ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e(TAG, "连接成功");
                // 当Service连接建立成功后,提供给客户端与Service交互的对象(根据Android Doc翻译的,不知道准确否。。。。)
                myService = ((LocalService.LocalBinder) service).getService();
            }


            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e(TAG, "断开连接");
                myService = null;
            }
        };
    }


4.activity_mani.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="启动Service" />
    <Button android:id="@+id/stop" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="停止Service" />
    <Button android:id="@+id/bind" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="绑定Service" />
    <Button android:id="@+id/unbind" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="解除Service" />
</LinearLayout>


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...