upnp协议学习笔记一

/**
 * 测试UPNP协议 显法移动设备
 * 
 * @time 下午12:59:57
 * @author zhenhuayue
 * @Email [email protected]
 */
public class UPNP_DempActivity extends ListActivity {
// 设备列表适配器
private ArrayAdapter<DeviceDisplay> deviceAdapter;
private RegistryListener listener = new BrowseRegistryListener();
private AndroidUpnpService upnpService;


private int screenWidth, screenHeight;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels;
Log.e("tag", "屏幕大小为:" + screenWidth + "*" + screenHeight);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(screenWidth, screenHeight);


deviceAdapter = new ArrayAdapter<DeviceDisplay>(UPNP_DempActivity.this, android.R.layout.simple_list_item_1);
setListAdapter(deviceAdapter);
// 绑定数据
getApplicationContext().bindService(new Intent(this, AndroidUpnpServiceImpl.class), serviceConnection, Context.BIND_AUTO_CREATE);


}


@Override
protected void onResume() {
super.onResume();
if (null != upnpService) {
upnpService.getRegistry().addListener(listener);
}
showNotification();
}


@Override
protected void onDestroy() {
super.onDestroy();
if (null != upnpService) {
upnpService.getRegistry().removeListener(listener);// 移除监听
}


// 与service解除绑定
getApplicationContext().unbindService(serviceConnection);
// 删除标题栏信息
UPNP_DempActivity.this.stopService(new Intent(UPNP_DempActivity.this, ShowNotificationService.class));


}


/**
* @see 设备档案监听
* @time 下午02:08:51
* @author zhenhuayue
* @Email [email protected]
*/
class BrowseRegistryListener extends DefaultRegistryListener {
@Override
public void remoteDeviceDiscoveryStarted(Registry registry, RemoteDevice device) {
Log.e("tag", "开始搜索设备" + device.getDisplayString());
deviceAdded(device);
}


@Override
public void remoteDeviceDiscoveryFailed(Registry registry, final RemoteDevice device, final Exception ex) {
Log.e("tag", "搜索设备失败:" + device.getDisplayString() + "=>" + ex);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UPNP_DempActivity.this,
"Discovery failed of '" + device.getDisplayString() + "': " + (ex != null ? ex.toString() : "Couldn't retrieve device/service descriptors"),
Toast.LENGTH_LONG).show();
}
});
deviceRemoved(device);


}


@Override
public void remoteDeviceAdded(Registry registry, RemoteDevice device) {
Log.e("tag", "移动设备可见" + device.getDisplayString());
deviceAdded(device);
}


@Override
public void remoteDeviceUpdated(Registry registry, RemoteDevice device) {
Log.e("tag", "移动设备更新" + device.getDisplayString());
deviceAdded(device);
}


@Override
public void remoteDeviceRemoved(Registry registry, RemoteDevice device) {
Log.e("tag", "移动设备移除:" + device.getDisplayString());
deviceRemoved(device);


}


@Override
public void localDeviceAdded(Registry registry, LocalDevice device) {
Log.e("tag", "本地设备添加" + device.getDisplayString());
deviceAdded(device);
}


@Override
public void localDeviceRemoved(Registry registry, LocalDevice device) {
Log.e("tag", "本地设备移除" + device.getDisplayString());
deviceRemoved(device);
}


@Override
public void beforeShutdown(Registry registry) {
Log.e("tag", "在关闭之前设备的数量为:" + registry.getDevices().size());
}


@Override
public void afterShutdown() {
Log.e("tag", "开始搜索设备");


}


/**
* 添加设备
*/
@SuppressWarnings("rawtypes")
public void deviceAdded(final Device device) {
runOnUiThread(new Runnable() {


@Override
public void run() {
DeviceDisplay d = new DeviceDisplay(device);
int position = deviceAdapter.getPosition(d);
if (position >= 0) {
deviceAdapter.remove(d);
deviceAdapter.insert(d, position);
} else {
deviceAdapter.add(d);
}


}
});
}


/**
* @see 移除设备
*/
@SuppressWarnings("rawtypes")
public void deviceRemoved(final Device device) {
runOnUiThread(new Runnable() {
public void run() {
deviceAdapter.remove(new DeviceDisplay(device));
}
});
}


}


private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.e("tag", "serviceConnection()");
upnpService = (AndroidUpnpService) service;


deviceAdapter.clear();
for (Device device : upnpService.getRegistry().getDevices()) {
((BrowseRegistryListener) listener).deviceAdded(device);
}


upnpService.getRegistry().addListener(listener);


upnpService.getControlPoint().search();
}


public void onServiceDisconnected(ComponentName className) {
upnpService = null;
}


};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, R.string.search_lan).setIcon(android.R.drawable.ic_menu_search);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.e("tag", "search1");
if (item.getItemId() == 0 && upnpService != null) {
Log.e("tag", "search2");
upnpService.getRegistry().removeAllRemoteDevices();
upnpService.getControlPoint().search();
}
return false;
}


/************************* 常用方法 ***************************************************/
/**
* 在状态栏(标题栏)显示当前应用信息
*/
private void showNotification() {
Log.e("tag", "showNotification()");
Intent intent = new Intent(UPNP_DempActivity.this, ShowNotificationService.class);
intent.setAction(ShowNotificationService.ACTION);
startService(intent);

}

}


/**
 * @see 设备对象
 * @time 下午01:49:21
 * @author zhenhuayue
 * @Email [email protected]
 */
@SuppressWarnings("rawtypes")
public class DeviceDisplay {
Device device;


public DeviceDisplay(Device device) {
this.device = device;
}


public Device getDevice() {
return device;
}


@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DeviceDisplay that = (DeviceDisplay) o;
return device.equals(that.device);
}


@Override
public int hashCode() {
return device.hashCode();
}


@Override
public String toString() {
return device.isFullyHydrated() ? device.getDisplayString() : device.getDisplayString() + " *";
}
}



/**
 * 用于在状态栏(标题栏)显示本应用信息的服务
 * 
 * @time 上午09:55:06
 * @author zhenhuayue
 * @Email [email protected]
 */
public class ShowNotificationService extends Service {
public static String ACTION = "cn.yue.upnp.service.ShowNotificationService.SHOWNOTIFICATION";
private NotificationManager manager;
private List<ProcessInfo> processInfos;


/**
     * 
     */
@Override
public void onCreate() {
Log.e("tag", "showNotificationService is onCreate!");
// 取得消息管理器
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}


@Override
public void onStart(Intent intent, int startId) {
Log.e("tag", "showNotificationService  onStart()");
if (null != intent && !"".equals(intent)) {
createNotification(intent);
}
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("tag", "showNotificationService  onStartCommand()");
createNotification(intent);
return START_STICKY;
}


@Override
public void onDestroy() {
Log.e("tag", "showNotificationService  onDestroy()");
manager.cancel(R.string.app_name);
stopForeground(false);
}


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


/**
* 取得当前应用所占内存数
*/
private void getRunningAppProcess() {
// 取得activityManager
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
// 取得所有进程信息
List<RunningAppProcessInfo> runningAppProcessInfos = activityManager.getRunningAppProcesses();
processInfos = new ArrayList<ProcessInfo>();
// 遍历进程信息取得所需内容
for (RunningAppProcessInfo info : runningAppProcessInfos) {
ProcessInfo processInfo = new ProcessInfo();
processInfo.setPid(info.pid);
processInfo.setUid(info.uid);
processInfo.setProcessName(info.processName);
processInfo.setPkName(info.pkgList);


// 取得进程内存
int[] mempid = new int[] { info.pid };
android.os.Debug.MemoryInfo[] memoryInfo = activityManager.getProcessMemoryInfo(mempid);
processInfo.setMemSize(memoryInfo[0].dalvikPrivateDirty);


processInfos.add(processInfo);
}


}


/**
* 新建消息
*/
private void createNotification(Intent intent) {
// TODO 此处需要实时更新
int temp = 0;
String unit = "MB";
getRunningAppProcess();
if (processInfos.size() > 0) {
for (int i = 0; i < processInfos.size(); i++) {
temp += processInfos.get(i).getMemSize();
}


// 如果小于1024就显示kb,否则显示mb
if (temp < 1024) {
unit = "KB";
} else {
temp = temp / 1024;
unit = "MB";
}


}


CharSequence text = getText(R.string.app_name);
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
// 取得当前cpu占用率


// 设置启动对象
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, UPNP_DempActivity.class), 0);
notification.setLatestEventInfo(this, text, "RAM:" + temp + unit + "  \t  CPU:" + 0 + "%", pendingIntent);
// startForeground(R.string.app_name, notification);
setForeground(true);
manager.notify(R.string.app_name, notification);
}


}

你可能感兴趣的:(String,service,null,search,email,menu)