I am trying to detect keyboard is active or not (Outside my application) using accessibility service. For that i tried to read the notifications "choose keyboard" (When multiple key board are enabled). Following code is used.
public class KeyboardWatcher extends AccessibilityService {
boolean isConnected = false;
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
final String packagename = String.valueOf(event.getPackageName());
Log.d("Package", packagename);
String msg = "";
List<CharSequence> s = event.getText();
if(s.iterator().hasNext())
{
msg += s.iterator().next().toString();
Log.d("MSG", msg);
}else{
Log.d("TYPE", event.getEventType()+"");
}
}else{
Log.d("EVENT TYPE__",event.getEventType()+"");
final String packagename = String.valueOf(event.getPackageName());
Log.d("PNE", packagename);
}
}
protected void onServiceConnected() {
if (isConnected) {
return;
}
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
setServiceInfo(info);
isConnected = true;
}
}
Now all notifications are logged by the application except "keyboard chooser" notification. How to read that notification, is that possible.
Thanks
package com.sat.app.notification;
import android.content.Context;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String title = sbn.getNotification().extras.getString("android.title");// It will be select keyboard
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("com.sat","Notification Removed");
}
}
IN Manifest : add
<service android:name="com.sat.app.notification.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
After installing application allow reading notification in settings.
Tested and working on Android 5.0
If I am correct there is no way to get that notification, the system itself detects all the available keyboards and displays them (if there is only one keyboard there will be no pop).
As far as I know there is no way to get that notification.
Related
I have an app that runs on 2 phones and allows the user to connect from one to the other using WifiP2p (WiFi Direct). On most phones, it works. Both phones go into peer discovery, they discover each other, one initiates a connection, and the other accepts. But when I try to connect to a Sony LT25i running Android 4.1.2, the pairing fails.
The code for initiating the connection is like this:
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig();
wifiP2pConfig.deviceAddress = device.deviceAddress;
// Try to make a device that supports WifiDirect the group owner,
// so that a legacy device can connect to it as an access point.
wifiP2pConfig.groupOwnerIntent = 10;
// Wifi Protected Setup: Push Button Configuration. The other main option is PIN configuration.
wifiP2pConfig.wps.setup = WpsInfo.PBC;
mWifiP2pManager.connect(mChannel, wifiP2pConfig, new WifiP2pManager.ActionListener() {...
Unexpected group creation, remove network
When the problem occurs, when the initiating device runs the above code to attempt to connect, the Sony shows this interesting tidbit in Logcat:
02-02 05:22:55.494 669-781/? E/WifiP2pService: Unexpected group creation,
remove network: DIRECT-aq-LG Phoenix 2
isGO: false
GO: Device:
deviceAddress: de:0b:34:f0:11:78
primary type: null
secondary type: null
wps: 0
grpcapab: 0
devcapab: 0
status: 4
interface: p2p0
where "LG Phoenix 2" is the name of the phone initiating the pairing.
For some reason, WifiP2pService doesn't like the fact that a group is being created, and removes it. Why?
I looked up the error message "WifiP2pService: Unexpected group creation, remove"
and found this code in WifiP2pService.DefaultState.processMessage():
/* unexpected group created, remove */
case WifiMonitor.P2P_GROUP_STARTED_EVENT:
mGroup = (WifiP2pGroup) message.obj;
loge("Unexpected group creation, remove " + mGroup);
mWifiNative.p2pGroupRemove(mGroup.getInterface());
break;
So apparently this happens because the WifiP2pService is in DefaultState? By contrast, WifiP2pService.P2pEnabledState.processMessage() doesn't have a case for P2P_GROUP_STARTED_EVENT. So maybe if the WifiP2pService were in the P2pEnabledState on the phone, I wouldn't be having this group removal problem.
But according to the logs, WifiP2p is enabled: I'm catching the WIFI_P2P_STATE_CHANGED_ACTION broadcast and logging the value of EXTRA_WIFI_STATE. So why is WifiP2pService apparently in DefaultState?
By the way, pairing used to work on the Sony, but yesterday I connected the device to my home Wifi router and it doesn't seem to have worked ever since, even though I disconnected it from the router.
I've tried turning off Wifi, turning it back on, removing ("forgetting") my home Wifi router, and rebooting the phones, and connecting from other phones besides the LG. Nothing fixes the problem.
This code that you have is very incomplete and needs to be completed. Note the sample of the code for you.
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener;
import android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.example.android.wifidirect.discovery.WiFiChatFragment.MessageTarget;
import com.example.android.wifidirect.discovery.WiFiDirectServicesList.DeviceClickListener;
import com.example.android.wifidirect.discovery.WiFiDirectServicesList.WiFiDevicesAdapter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WiFiServiceDiscoveryActivity extends Activity implements
DeviceClickListener, Handler.Callback, MessageTarget,
ConnectionInfoListener {
public static final String TAG = "wifidirectdemo";
// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = "_wifidemotest";
public static final String SERVICE_REG_TYPE = "_presence._tcp";
public static final int MESSAGE_READ = 0x400 + 1;
public static final int MY_HANDLE = 0x400 + 2;
private WifiP2pManager manager;
static final int SERVER_PORT = 4545;
private final IntentFilter intentFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private WifiP2pDnsSdServiceRequest serviceRequest;
private Handler handler = new Handler(this);
private WiFiChatFragment chatFragment;
private WiFiDirectServicesList servicesList;
private TextView statusTxtView;
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
statusTxtView = (TextView) findViewById(R.id.status_text);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
startRegistrationAndDiscovery();
servicesList = new WiFiDirectServicesList();
getFragmentManager().beginTransaction()
.add(R.id.container_root, servicesList, "services").commit();
}
#Override
protected void onRestart() {
Fragment frag = getFragmentManager().findFragmentByTag("services");
if (frag != null) {
getFragmentManager().beginTransaction().remove(frag).commit();
}
super.onRestart();
}
#Override
protected void onStop() {
if (manager != null && channel != null) {
manager.removeGroup(channel, new ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
}
});
}
super.onStop();
}
/**
* Registers a local service and then initiates a service discovery
*/
private void startRegistrationAndDiscovery() {
Map<String, String> record = new HashMap<String, String>();
record.put(TXTRECORD_PROP_AVAILABLE, "visible");
WifiP2pDnsSdServiceInfo service = WifiP2pDnsSdServiceInfo.newInstance(
SERVICE_INSTANCE, SERVICE_REG_TYPE, record);
manager.addLocalService(channel, service, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Added Local Service");
}
#Override
public void onFailure(int error) {
appendStatus("Failed to add a service");
}
});
discoverService();
}
private void discoverService() {
/*
* Register listeners for DNS-SD services. These are callbacks invoked
* by the system when a service is actually discovered.
*/
manager.setDnsSdResponseListeners(channel,
new DnsSdServiceResponseListener() {
#Override
public void onDnsSdServiceAvailable(String instanceName,
String registrationType, WifiP2pDevice srcDevice) {
// A service has been discovered. Is this our app?
if (instanceName.equalsIgnoreCase(SERVICE_INSTANCE)) {
// update the UI and add the item the discovered
// device.
WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
.findFragmentByTag("services");
if (fragment != null) {
WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
.getListAdapter());
WiFiP2pService service = new WiFiP2pService();
service.device = srcDevice;
service.instanceName = instanceName;
service.serviceRegistrationType = registrationType;
adapter.add(service);
adapter.notifyDataSetChanged();
Log.d(TAG, "onBonjourServiceAvailable "
+ instanceName);
}
}
}
}, new DnsSdTxtRecordListener() {
/**
* A new TXT record is available. Pick up the advertised
* buddy name.
*/
#Override
public void onDnsSdTxtRecordAvailable(
String fullDomainName, Map<String, String> record,
WifiP2pDevice device) {
Log.d(TAG,
device.deviceName + " is "
+ record.get(TXTRECORD_PROP_AVAILABLE));
}
});
// After attaching listeners, create a service request and initiate
// discovery.
serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
manager.addServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Added service discovery request");
}
#Override
public void onFailure(int arg0) {
appendStatus("Failed adding service discovery request");
}
});
manager.discoverServices(channel, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Service discovery initiated");
}
#Override
public void onFailure(int arg0) {
appendStatus("Service discovery failed");
}
});
}
#Override
public void connectP2p(WiFiP2pService service) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = service.device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
if (serviceRequest != null)
manager.removeServiceRequest(channel, serviceRequest,
new ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int arg0) {
}
});
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
appendStatus("Connecting to service");
}
#Override
public void onFailure(int errorCode) {
appendStatus("Failed connecting to service");
}
});
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d(TAG, readMessage);
(chatFragment).pushMessage("Buddy: " + readMessage);
break;
case MY_HANDLE:
Object obj = msg.obj;
(chatFragment).setChatManager((ChatManager) obj);
}
return true;
}
#Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo p2pInfo) {
Thread handler = null;
/*
* The group owner accepts connections using a server socket and then spawns a
* client socket for every client. This is handled by {#code
* GroupOwnerSocketHandler}
*/
if (p2pInfo.isGroupOwner) {
Log.d(TAG, "Connected as group owner");
try {
handler = new GroupOwnerSocketHandler(
((MessageTarget) this).getHandler());
handler.start();
} catch (IOException e) {
Log.d(TAG,
"Failed to create a server thread - " + e.getMessage());
return;
}
} else {
Log.d(TAG, "Connected as peer");
handler = new ClientSocketHandler(
((MessageTarget) this).getHandler(),
p2pInfo.groupOwnerAddress);
handler.start();
}
chatFragment = new WiFiChatFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_root, chatFragment).commit();
statusTxtView.setVisibility(View.GONE);
}
public void appendStatus(String status) {
String current = statusTxtView.getText().toString();
statusTxtView.setText(current + "\n" + status);
}
}
And the file for your AndroidManifast.xml should be the same and give these accesses
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Google Play filtering -->
<uses-feature android:name="android.hardware.wifi.direct" android:required="true"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".WiFiServiceDiscoveryActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
If you have any questions, let me respond as quickly as possible
SOURCE
WiFiDirectServiceDiscovery
I am basically working with Android Application , i have requirement to restrict to open others apps while my app is running, Means My app is running it will put some locks on other application while i am accessing the others app, Kind of Application Lock. I am trying but could not find good solution. If any buddy have some idea or link or sample code please share to me.
Basically you want Kiosk Mode .
Try this:
Home button press:
<category android:name="android.intent.category.HOME" /> //add in manifest
What id does: whenever you press the home button, all the applications installed in your phone which have category.HOME category in intent-filter in their AndroidManifest.xml will be listed .
then handle Long press Home Button:
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
for this add this line in manifest :
<uses-permission android:name="android.permission.REORDER_TASKS" />
3.handle BackButton :
#Override
public void onBackPressed() {
// Stop user to exit
// super.onBackPressed();
}
You can also try this for Kiosk Mode:
Read this document
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.provider.SyncStateContract;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class HeartBeat extends Service {
private static final String TAG = HeartBeat.class.getSimpleName();
public Timer TIMER;
// private static Set<AccessGranted> mAccessGrantedList = new HashSet<AccessGranted>();
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
// private BroadcastReceiver mAccessGrantedReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
String prefix;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, HeartBeat.class));
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
//Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
// Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, HeartBeat.class));
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
Set keySet = allEntries.keySet();
Iterator<String> keySetIter = keySet .iterator();
while (keySetIter.hasNext()) {
String keyEntry= keySetIter.next();
Log.e("Shared Vaues",keyEntry);
}
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
packagezList.add(entry.getKey());
Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());
}
/* for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
//Check if the package name starts with the prefix.
if (entry.getKey().startsWith(prefix)) {
//Add JUST the package name (trim off the prefix).
packagezList.add(entry.getKey().substring(prefix.length()));
packagezList.add(entry.getKey());
}
}*/
for(Object object: packagezList){
Log.e("YO!", (String) object);
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
Log.e("activity on Top", "" + activityOnTop);
Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
// Provide the packagename(s) of apps here, you want to show password activity
if (!activityOnTop.contains(getApplicationContext().getPackageName()))
// if(!activityOnTop.contains(getApplicationContext().getPackageName()))
{ // you have to make this check even better
Intent i = new Intent(getApplicationContext(), LockScreenActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.putExtra( "", "");
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
I am developing an app which uses getRunningTasks() function to get the top activity name. But getRunningTasks() is deprecated in Android L. Is there any other way to get the top activity name (not package name) in Lollipop.
Class<?> currentClassName; // Declare Globally
Activity activity = (Activity) context;//casting context into activity
try
{
currentClassName = Class.forName(activity.getClass().getName()); //getting the current activity's class name from activity object
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
Please read SO Answer
I found a solution to get top activity name on Lollipop with the new Class UsageStatsManager added in Android L.
First you need the permission
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
And the user must enable this option.
Then use this method queryEvents()
There is a simple example.
while (true) {
final long INTERVAL = 1000;
final long end = System.currentTimeMillis();
final long begin = end - INTERVAL;
final UsageEvents usageEvents = manager.queryEvents(begin, end);
while (usageEvents.hasNextEvent()) {
UsageEvents.Event event = new UsageEvents.Event();
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
Log.d("event", "timestamp : " + event.getTimeStamp());
Log.d("event", "package name : " + event.getPackageName());
Log.d("event", "class name : " + event.getClassName());
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
When an activity become to foreground, you can see its class name and package name in Logcat.
AccessibilityService can resolve this requirement, but the Accessibilityservice
api in android not stable, sometimes need checkbox off and on again, some code
<application>
<service
android:name=".service.DetectService"
android:exported="false"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibility_service" />
</service>
<?xml version="1.0" encoding="UTF-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackAllMask"
android:accessibilityFlags="flagReportViewIds"
android:canPerformGestures="true"
android:canRetrieveWindowContent="true"
android:notificationTimeout="100" />
import android.accessibilityservice.AccessibilityService;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
public class DetectService extends AccessibilityService {
#Override
protected void onServiceConnected() {
super.onServiceConnected();
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null) {
return;
}
Log.d("DetectService", "type: " + event.getEventType());
CharSequence packageName = source.getPackageName();
if (event.getEventType() != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
return;
}
ComponentName componentName = new ComponentName(event.getPackageName().toString(), event.getClassName().toString());
try {
String activityName = getPackageManager().getActivityInfo(componentName, PackageManager.GET_META_DATA
| PackageManager.MATCH_ALL).toString();
activityName = activityName.substring(activityName.indexOf(" "), activityName.indexOf("}"));
Log.e("DetectService", packageName + ": " + activityName);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
// sometime getActivityInfo will get NameNotFoundException,try use componentName
}
}
#Override
public void onInterrupt() {
Log.w("DetectService", "onInterrupt");
}
#Override
public boolean onUnbind(Intent intent) {
Log.w("DetectService", "onUnbind");
return super.onUnbind(intent);
}
}
I am sure this is simple but I cannot figure it out. All I am trying to do is send a message via NFC. The code I have work perfectly if I am sending it to the main activity, but I don't know how to send it to a different activity. I have looked over both the NFC and Intent Filter articles on the Android Developer pages but am still not sure exactly how to do this. I am trying to send it to a NFC activity, I will post my manifest and NFC class below.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.justbaumdev.tagsense"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo" >
<activity
android:name=".TagSense"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.justbaumdev.tagsense.NFC" android:exported="false">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.justbaumdev.tagsense" />
</intent-filter>
</activity>
</application>
</manifest>
NFC Class:
package com.justbaumdev.tagsense;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;
public class NFC extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nfc);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // Check for available NFC Adapter
if (mNfcAdapter == null)
{
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
else
{
mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to set NDEF message
mNfcAdapter.setOnNdefPushCompleteCallback(this, this); // Register callback to listen for message-sent success
}
}
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String mac = wm.getConnectionInfo().getMacAddress();
String newMac = mac.substring(0, 2);
mac = mac.substring(2);
int hex = Integer.parseInt(newMac, 16) + 0x2;
newMac = Integer.toHexString(hex);
String text = newMac + mac;
NdefMessage msg = new NdefMessage(NdefRecord.createMime(
"application/com.justbaumdev.tagsense", text.getBytes()));
return msg;
}
/**
* Implementation for the OnNdefPushCompleteCallback interface
*/
#Override
public void onNdefPushComplete(NfcEvent arg0) {
// A handler is needed to send messages to the activity when this
// callback occurs, because it happens from a binder thread
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
/** This handler receives a message from onNdefPushComplete */
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SENT:
Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
break;
}
}
};
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
//TODO Currently overwrites any previously saved mac addresses. Get FB ID as value. Auto end activity.
void processIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
//textView.setText(new String(msg.getRecords()[0].getPayload()));
String payload = new String(msg.getRecords()[0].getPayload());
Toast.makeText(this, new String(msg.getRecords()[0].getPayload()), Toast.LENGTH_LONG).show();
SharedPreferences appData = getSharedPreferences("appData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appData.edit();
String addresses = appData.getString("mac_address", null);
if(addresses==null)
{
JSONArray addressArray = new JSONArray();
addressArray.put(payload);
addresses = addressArray.toString();
}
else
{
try {
if(!addresses.contains(payload))
{
JSONArray addressArray = new JSONArray(addresses);
addressArray.put(payload);
addresses = addressArray.toString();
}
} catch (JSONException e) {
Toast.makeText(this, "Error adding new friend. Please try again.", Toast.LENGTH_SHORT).show();
}
}
editor.putString("mac_address", addresses);
editor.commit();
}
}
Thanks for your help.
Remove the attribute android:exported="false". See also https://stackoverflow.com/a/12719621/1202968
I am trying to connect 2 Android devices through Wi-fi Direct.
In my application I am hard coding the MAC address of the other device and calling the method connect. I am assuming that Wi-Fi Direct is on in both the devices. Here is the code I am using:
package com.abc;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.widget.Toast;
public class WiFiDirectActivity extends Activity {
/** Called when the activity is first created. */
protected WifiP2pManager manager;
protected Channel channel;
public WifiP2pConfig config ;
protected final IntentFilter intentFilter = new IntentFilter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intentFilter.addAction (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, this.getMainLooper(), null);
config = new WifiP2pConfig();
config.deviceAddress = "78:d6:f0:ab:d9:da";
config.groupOwnerIntent = 0;
config.wps.setup = WpsInfo.PBC;
manager.connect(channel, config, new WifiP2pManager.ActionListener(){
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG);
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG);
}
});
}
}
but it is not connecting. What is wrong with my implementation?
I have a similar code working, the main differences are:
I get the device address calling before to discovery peers (If you do that then you have to add WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION to intent filter group)
I don't set the config.groupOwnerIntent
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = this.address;
config.wps.setup = WpsInfo.PBC;
register a BroadcastReceiver in onResume() and override it. remember to unregister it in onPause()
private class WiFiDirectBroadcastReceiver extends android.content.BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
//TODO
}
}
}
then try to call discoverPeers() first
mWifiP2pManager.discoverPeers(Channel mChannel, ActionListener mActionListener);
if discoverPeers() does find peers, action WIFI_P2P_PEERS_CHANGED_ACTION will be triggered.
we can call requestPeers() in WIFI_P2P_PEERS_CHANGED_ACTION in the BroadcastReceiver
mWifiP2pManager.requestPeers(Channel mChannel, WifiP2pManager.PeerListListener);
so our BroadcastReceiver now looks like this
private class WiFiDirectBroadcastReceiver extends android.content.BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
mWifiP2pManager.requestPeers(mChannel , pl);
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
//TODO
}
}
}
to implement WifiP2pManager.PeerListListener, you need to override onPeersAvailable(WifiP2pDeviceList peers)
in onPeersAvailable(), the parameter wifiP2pDeviceList means the peers you discovered
we need a UI object to let us choose which device to connect, so I use spinner here.
also you can use listView or something else.
private List<WifiP2pDevice> mPeers = new ArrayList<WifiP2pDevice>();
spinnerAdapter = new WiFiPeerListAdapter(this, R.layout.row_devices, mPeers);
...
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
mPeers.clear();
mPeers.addAll(wifiP2pDeviceList.getDeviceList());
spinnerAdapter.notifyDataSetChanged();
}
finally we can connect to a device
WifiP2pDevice device = spinnerAdapter.getItem((int) mSpinner.getSelectedItemId());
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
mWifiP2pManager.connect(mChannel, config, mActionListener);
after two device connected, BroadcastReceiver action WIFI_P2P_CONNECTION_CHANGED_ACTION will be triggered. so we can do something here.
our BroadcastReceiver now looks like
private class WiFiDirectBroadcastReceiver extends android.content.BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
//TODO
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
mWifiP2pManager.requestPeers(mChannel , pl);
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
Log.d(TAG,networkInfo.toString());
if (networkInfo.isConnected()) {
mWifiP2pManager.requestConnectionInfo(mChannel, WifiP2pManager.ConnectionInfoListener);
}
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
//TODO
}
}
}
btw, the log in action WIFI_P2P_CONNECTION_CHANGED_ACTION will get something like this
NetworkInfo: type: WIFI_P2P[], state: UNKNOWN/IDLE, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true, simId: 0
now we need to implement WifiP2pManager.ConnectionInfoListener and override its abstract method onConnectionInfoAvailable(WifiP2pInfo info) for requestConnectionInfo()
private WifiP2pInfo p2pInfo;
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
p2pInfo = info;
mWifiP2pManager.requestGroupInfo(mChannel, WifiP2pManager.GroupInfoListener);
}
again we need to implement WifiP2pManager.GroupInfoListener and override onGroupInfoAvailable(WifiP2pGroup group)
#Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
String log;
if(wifiP2pGroup.isGroupOwner()) {
log = "I am GO";
}else{
log = "I am not GO";
}
Log.d(TAG, log);
}
now we almost got every info about these two devices
enjoy it