android之远程启动服务

启动远程服务和隐式启动Activity一样

实现一个服务


为了演示方便,该服务是一个空服务

package xidian.dy.com.chujia;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by dy on 2016/7/12.
 */

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在清单文件中注册该服务


在清单文件中注册服务和注册Activity一样,都是类的注册

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xidian.dy.com.chujia">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="主界面">
        <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="xidian.dy.com.MyService"/>
        </intent-filter>
    </service>
</application>
</manifest>

调用远程服务


调用远程服务和隐式启动Activity一样

package xidian.dy.com.chujia;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Intent service;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        service = new Intent();
        service.setAction("xidian.dy.com.MyService");
        startService(service);
    }

}

 

posted @ 2016-07-17 09:48  被罚站的树  阅读(885)  评论(0编辑  收藏  举报