手机应用可以作为桌面应用的辅助工具,用来接收桌面应用的状态信息。这里介绍如何实现一个简单的Android程序用于接收Windows扫描仪应用的工作状态。
参考:How to Push Notifications to Android Applications from Windows
思路
-
创建socket连接用于应用通信
-
Android上启动后台服务,用于接收信息
-
在收到信息之后,后台服务会把推送消息发送给Android应用
Socket信息发送
使用TCPListener来创建socket连接,相关内容可以参考:Wireless TWAIN Document Scanning on Android
启动停止Android Service
创建服务NotificationService:
public class NotificationService extends Service {
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
在AndroidManifest.xml中申明一下这个service:
<
service android:name = "com.dynamsoft.twain.NotificationService"
/>
在onCreate(Bundle)中启动服务:
startService(new Intent(ScanAssist.this, NotificationService.class));
在onDestroy()中停止服务:
stopService(new Intent(ScanAssist.this, NotificationService.class));
推送Android通知
调用NotificationManager:
private NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
创建用于内容显示的Activity IncomingMessageView:
public class IncomingMessageView extends Activity {
public static final String KEY_FROM = "from";
public static final String KEY_MESSAGE = "message";
public static final int NOTIFICATION_ID = R.layout.activity_main;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView view = new TextView(this);
view.setText(getIntent().getCharSequenceExtra(KEY_FROM) + ": " + getIntent().getCharSequenceExtra(KEY_MESSAGE));
setContentView(view);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
}
}
在AndroidManifest.xml中申明Activity:
<activity android:name="com.dynamsoft.twain.IncomingMessageView" android:label="@string/app_name" > </activity>
发送消息,并显示在状态栏上:
Intent notifyIntent = new Intent(this, IncomingMessageView.class);
notifyIntent.putExtra(IncomingMessageView.KEY_FROM, from);
notifyIntent.putExtra(IncomingMessageView.KEY_MESSAGE, message);
PendingIntent pendingIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_ONE_SHOT
);
Notification notif = new Notification.Builder(this)
.setContentTitle("TWAIN Scanner Status ")
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker(message)
.build();
notif.defaults = Notification.DEFAULT_ALL;
mNM.notify(IncomingMessageView.NOTIFICATION_ID, notif);
用例
-
运行Android应用,启动服务
-
应用切换到后台,操作其它应用,比如打开浏览器
-
在Windows上操作应用,点击文件扫描
-
扫描成功之后,信息发送到手机
源码
https://github.com/DynamsoftRD/ScanAssist
git clone https://github.com/DynamsoftRD/ScanAssist.git