1. 引言:
上篇已经将服务进行了分类, 从本篇开始,将对每种类型的服务给出一个实例。
本篇主要实例: 应用服务之本地服务的开启和运用。这种服务的特点在上篇已进行了说明,它与App处于同一个进程,关于更多 的关于这种服务的说明,这里不再叙述。
下面,进行举例:
2. 例子说明:
(1). 功能: 创建service,在service中查找指定的apk(用包名进行遍历匹配),如果找到,通过handler传递给UI,在UI中显示这些包名。
(2). 您将学到:
a. service中handler的运用;
b. 通过接口的方式回传到UI层。c. Service的定义和运用。
3. 例子代码:
(1). PackageFindService:
package com.example.androidservicetest;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class PackageFindService extends Service {
private static String[] pkgs = new String[] {"com.tencent.mm","com.tencent.mobileqq",
"com.tencent.qqmusic",
"com.sina.weibo"
};
private PackageFindListener mPackageFindListener;
public class LocalBinder extends Binder {
public PackageFindService getService() {
Log.i("TAG", "getService ---> " + PackageFindService.this);
return PackageFindService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i("TAG", "onBind======================");
return new LocalBinder();
}
@Override
public void onCreate() {
super.onCreate();
Log.i("TAG", "onCreate======================");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("TAG", "onDestroy======================");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i("TAG", "onStart======================");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("TAG", "onStartCommand======================");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Log.i("TAG", "onUnbind======================");
return super.onUnbind(intent);
}
/**
* Find主函数
*/
private void FindPackages() {
List<PackageInfo> list = this.getPackageManager().getInstalledPackages(0);
if (list == null || list.size() < 1) {
return ;
}
for (PackageInfo pkInfo : list) {
// 去掉本应用
if (pkInfo.applicationInfo.packageName.equals(this.getPackageName())) {
continue;
}
for (int i = 0; i<pkgs.length; i++) {
if (pkInfo.applicationInfo.packageName.contains(pkgs[i])) {
Message msg = new Message();
msg.what = 1;
msg.getData().putString("name", pkInfo.applicationInfo.packageName);
MyHandler.sendMessage(msg);
//mPackageFindListener.onFindResult(true, pkInfo.applicationInfo.packageName); // 一定得用handler的方式通知listerner,,而这个liserner其实是为显示UI用的。
}
}
}
}
// find thread
public void startFindThread(){
new Thread(new Runnable() {
@Override
public void run() {
FindPackages();
//find 完成后,由listener进行unbind
Message msg = new Message();
msg.what = 2;
MyHandler.sendMessage(msg);
}
}).start();
}
Handler MyHandler = new Handler() {
public void handleMessage(Message msg) {
int what = msg.what;
if (msg.what == 1) {
String pakName = msg.getData().getString("name");
mPackageFindListener.onFindResult(true, pakName);
} else {
mPackageFindListener.onFindResult(false, null);
}
};
};
/**
* 注册回调接口的方法,供外部调用
*/
public void setListener(PackageFindListener listener) {
this.mPackageFindListener = listener;
}
}
(2). PackageFindListener:
package com.example.androidservicetest;
public interface PackageFindListener {
public void onFindResult(boolean isFind, String pkgName);
}
(3). MainActivity:
package com.example.androidservicetest;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static String TAG = "MainActivity";
private TextView textView;
private String textStr = "";
private PackageFindService mPackageFindService;
private ServiceConnection conn;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textview);
textView.setText("Find:");
mContext = this;
startFindService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void startFindService() {
// 创建ServiceConnection
conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder service) {
Log.i(TAG, "onServiceConnected ====================begin");
mPackageFindService = ((PackageFindService.LocalBinder) service)
. getService();
mPackageFindService. setListener(new PackageFindListener() {
@Override
public void onFindResult(boolean isFind, String pkgName) {
if (isFind) {
textStr = textStr + pkgName + ";";
textView.setText(textStr);
}else if (pkgName == null) {
mContext.unbindService(conn);
}
}
});
if (mPackageFindService != null) {
mPackageFindService
.startFindThread();
}
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
};
// 绑定Service
Intent intent = new Intent("com.test.service");
this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
内部类,也可以用这种方式进行listener的定义。
// private PackageFindListener mPackageFindListener;
// class MyPackageFindListener implements PackageFindListener {
//
// @Override
// public void onFindResult(boolean isFind, String pkgName) {
// if (isFind) {
// textStr = textStr + pkgName + ";";
// textView.setText(textStr);
// }
// }
//
// }
}
(4). AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidservicetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidservicetest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.androidservicetest.PackageFindService" >
<intent-filter>
<action android:name=" com.test.service"/>
</intent-filter>
</service>
</application>
</manifest>
4. 测试结果:
运行程序后,在屏幕上将会显示:
com.sina.weibo;com.tencent.mm;com.tencent.mobileqq;
5. 实例代码下载(包含了远程服务测试实例):
http://download.csdn.net/detail/liranke/8401933