Blocking any other application via Service - java

I'm creating a business application and must block any other application that the user tries to open. I am creating a service to it, but it's not working.
When run, it does not see the other applications when opened by the user.
I read some other posts here, but I could not solve.
Below is my service.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
startService(new Intent(this, clsServico.class));
}
my class:
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class clsServico extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // em segundos
private static final String TAG = clsServico.class.getSimpleName();
private static final String APS_BG = "APS_BG";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
ctx = this;
// checa periodicamente se tem algum outro app na tela
t = new Thread(new Runnable() {
#Override
public void run() {
do {
//checkAPS();
try {
if(Build.VERSION.SDK_INT >= 21)
listTasks();
else
listTasks_SDK21();
} catch (PackageManager.NameNotFoundException e) {
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
public void listTasks() throws PackageManager.NameNotFoundException {
if(Build.VERSION.SDK_INT >= 21) {
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
String packagename;
String label;
for (ActivityManager.AppTask task : tasks) {
packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
//Log.i(TAG, packagename + ":" + label);
}
}
}
public void listTasks_SDK21() throws PackageManager.NameNotFoundException {
ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = mgr.getRecentTasks(20, 0);
String packagename;
String label;
for(ActivityManager.RecentTaskInfo task: tasks){
packagename = task.baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
Log.i(TAG,packagename + ":" + label);
}
}
private void checkAPS() {
/*
if(apenasAPSAtivado(ctx)) {
if(isInBackground()) {
restoreApp(); // tras p frente
}
}
*/
PackageManager packageManager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ResolveInfo> appList = packageManager.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(packageManager));
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
ApplicationInfo a = p.applicationInfo;
// skip system apps if they shall not be included
if((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
continue;
}
//Log.i("packageName","" + p.packageName);
}
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo run = RunningTask.get(0);
Log.i("topActivity", run.topActivity.getClassName());
Intent ints = new Intent(Intent.ACTION_MAIN, null);
ints.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> intentlist = packageManager.queryIntentActivities(ints, PackageManager.PERMISSION_GRANTED);
List<ActivityManager.RunningTaskInfo> processes = mActivityManager.getRunningTasks(Integer.MAX_VALUE);
String pName = "";
if (processes != null)
{
for (int i = 0; i < processes.size(); i++) {
String packageName = processes.get(i).topActivity.getPackageName();
ActivityManager.RunningTaskInfo temp = processes.get(i);
try
{
pName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
//Log.i("RunningTaskInfo",pName + " : " + temp.id);
/*
if (savedapp.equals(pName)) {
// finish(pm.);
int code = intentlist.get(i).activityInfo.hashCode();
finishActivity(code);
mActivityManager.killBackgroundProcesses(packageName);
mActivityManager.restartPackage(packageName);
android.os.Process.killProcess(temp.id);
finishActivity(temp.id);
}
*/
}
}
List<ActivityManager.RunningTaskInfo> rt = mActivityManager.getRunningTasks(1000);
for(int i = 0; i < rt.size(); i++){
ActivityManager.RunningTaskInfo ar = rt.get(i);
String activityOnTop=ar.topActivity.getClassName();
//Log.i("rt", activityOnTop);
}
//ActivityManager.RunningTaskInfo ar = rt.get(0);
//String activityOnTop=ar.topActivity.getClassName();
//Log.i("activityOnTop", activityOnTop);
//ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = mActivityManager.getRunningAppProcesses();
for(int i = 0; i < pids.size(); i++)
{
ActivityManager.RunningAppProcessInfo p = pids.get(i);
if(!p.processName.equalsIgnoreCase("nog.aps3")){
android.os.Process.killProcess(p.pid);
try {
android.os.Process.killProcess(p.pid);
android.os.Process.sendSignal(p.pid, android.os.Process.SIGNAL_KILL);
mActivityManager.killBackgroundProcesses(p.processName);
} catch (Exception e) {
e.printStackTrace();
//Log.i("try", e.toString());
}
}
//Log.i("info.processName", p.processName);
//isInBackground();
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
//Log.i("getPackageName", ctx.getApplicationContext().getPackageName() +" =? "+ componentInfo.getPackageName());
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
//restore other class
}
public boolean apenasAPSAtivado(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(APS_BG, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Can anyone help me with this, pls?

Related

How to do realtime network in Doze Mode

I am trying to do realtime bluetooth location tracking using Android. I want to scan for bluetooth le and upload to a server in real time even when the phone is locked.
When running the app however, after 30 minutes the network request queue stops being processed because of Android's built-in Doze Mode.
I've tried moving my background service to the foreground but to no avail.
Any ideas how I can do constant network in Doze Mode? This won't be a public app so won't be submitted to Google Play, it will only be installed to Enterprise devices.
My Service Class:
package REDACTED.beaconlistener;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.RejectedExecutionException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
public class BroadcastService extends Service {
private static final String TAG = "BROADCAST";
private static final String strURL = "REDACTED";
private long lastAlertTimestamp;
private ScanCallback callback;
private Timer timer;
private BluetoothLeScanner scanner;
private ScanSettings settings;
private PowerManager.WakeLock wakeLock;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("My Notification")
.setContentText("My Message")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.setTicker("TICKER TEXT")
.build();
startForeground(999, notification);
lastAlertTimestamp = Calendar.getInstance().getTime().getTime() / 1000;
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Log.e(TAG, "Bluetooth LE not supported!");return;
}
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
scanner = bluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
callback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
if (result.getDevice().getAddress().substring(0, 8).equals("0C:F3:EE")) {
// Its a pill!
String[] vcodeArr = result.getDevice().getAddress().substring(9).split(":");
String vcode = vcodeArr[2] + vcodeArr[1] + vcodeArr[0];
Log.d("SCANNER", vcode + " : " + String.valueOf(result.getRssi() + 128));
Long ts = System.currentTimeMillis()/1000;
PingUrlTask task = new PingUrlTask();
try {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, strURL, vcode, String.valueOf(result.getRssi() + 128), getUniquePsuedoID(), ts.toString());
} catch(RejectedExecutionException e) {
Log.e("BROADCAST", "RejectedExecutionException");
}
}
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
this.onScanResult(0, sr);
}
}
#Override
public void onScanFailed(int errorCode) {
// Do Nothing.
Log.e("SCANNER", String.valueOf(errorCode));
}
};
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
new PingUrlTask().execute(strURL, null, String.valueOf(0), getUniquePsuedoID());
} catch(Exception e) {
Log.e("BROADCAST", e.getMessage());
e.printStackTrace();
}
}
}, 10000, 10000);
try {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BeaconListener");
} catch(NullPointerException e) {
// Do nothing.
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ping("Service Started");
try {
wakeLock.acquire();
} catch(Exception e) {
// Do nothing.
}
// bluetoothAdapter.startLeScan(callback);
List<ScanFilter> filter = new ArrayList<ScanFilter>();
scanner.startScan(filter, settings, callback);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
try {
wakeLock.release();
} catch(Exception e) {
// Do nothing.
}
// bluetoothAdapter.stopLeScan(callback);
scanner.stopScan(callback);
timer.cancel();
ping("Service Stopped");
}
public String getUniquePsuedoID() {
// If all else fails, if the user does have lower than API 9 (lower
// than Gingerbread), has reset their device or 'Secure.ANDROID_ID'
// returns 'null', then simply the ID returned will be solely based
// off their Android device information. This is where the collisions
// can happen.
// Thanks http://www.pocketmagic.net/?p=1662!
// Try not to use DISPLAY, HOST or ID - these items could change.
// If there are collisions, there will be overlapping data
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
// Thanks to #Roman SL!
// https://stackoverflow.com/a/4789483/950427
// Only devices with API >= 9 have android.os.Build.SERIAL
// http://developer.android.com/reference/android/os/Build.html#SERIAL
// If a user upgrades software or roots their device, there will be a duplicate entry
String serial = null;
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
// Go ahead and return the serial for api => 9
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception exception) {
// String needs to be initialized
serial = "serial"; // some value
}
// Thanks #Joe!
// https://stackoverflow.com/a/2853253/950427
// Finally, combine the values we have found by using the UUID class to create a unique identifier
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
private void ping(String text) {
Log.d("BROADCAST", text);
// new PingUrlTask().execute(strURL);
}
private void createPushNotification(String title, String text) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setTicker("Hearty365")
.setContentTitle(title)
.setContentText(text)
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent)
.setContentInfo("Info")
.setPriority(Notification.PRIORITY_HIGH);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
}
private class PingUrlTask extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(final String... strURL) {
Log.d("BROADCAST", "PingUrlTask");
Log.d("BROADCAST", strURL[0]);
try {
URL requestUrl = new URL(strURL[0]);
HttpsURLConnection conn = (HttpsURLConnection) requestUrl.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(95 * 1000);
conn.setConnectTimeout(95 * 1000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-Environment", "android");
conn.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
if (strURL.length != 5) {
return null;
}
// Write Post data
StringBuilder queryParams = new StringBuilder();
queryParams.append("vcode=");
queryParams.append(strURL[1]);
queryParams.append("&rssi=");
queryParams.append(strURL[2]);
queryParams.append("&deviceId=");
queryParams.append(strURL[3]);
queryParams.append("&timestamp=");
queryParams.append(strURL[4]);
queryParams.append("&time=");
queryParams.append(lastAlertTimestamp);
Log.d("BROADCAST", queryParams.toString());
DataOutputStream dStream = new DataOutputStream(conn.getOutputStream());
dStream.writeBytes(queryParams.toString());
conn.connect();
// Read response
Log.d(TAG, String.valueOf(conn.getResponseCode()));
if (conn.getResponseCode() == 200) {
StringBuilder result = new StringBuilder();
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
Log.d(TAG, result.toString());
try {
JSONObject obj = new JSONObject(result.toString());
lastAlertTimestamp = obj.getLong("serverTime");
JSONArray alerts = obj.getJSONArray("alerts");
for(int i = 0; i < alerts.length(); i++) {
JSONObject alert = alerts.getJSONObject(i);
createPushNotification(alert.getString("alert_title"), alert.getString("alert_message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
dStream.flush();
dStream.close();
Log.d("BROADCAST", String.valueOf(conn.getResponseCode()));
} catch(Exception e) {
Log.e("BROADCAST", e.getMessage());
e.printStackTrace();
}
// Handler handler = new Handler(Looper.getMainLooper());
// handler.post(new Runnable() {
// #Override
// public void run() {
// if (MainActivity.mWebView != null) {
// try {
// JSONObject payload = new JSONObject();
// payload.put("vcode", strURL[1]);
// payload.put("rssi", strURL[2]);
// payload.put("deviceId", strURL[3]);
// payload.put("timestamp", strURL[4]);
// payload.put("time", lastAlertTimestamp);
// String command = String.format("androidData(%s)", payload.toString());
//
// Log.d(TAG, command);
// MainActivity.mWebView.evaluateJavascript(command, null);
// } catch(Exception e) {
// Log.d(TAG, e.getMessage());
// e.printStackTrace();
// }
// } else {
// Log.w(TAG, "No WebView!");
// }
// }
// });
return null;
}
}
}

Android TTS how to display speaking word in textview

How can i display tts output as text view when word speaking.
Actually i want to display tts output words in textview. I have 1 edittext in which i enter some data and then when click on play button it performs speech but i also want to display speaking words in text view how can i do this any one can help me. i also think about convert text into array form and then pass but, i don't think it useful any other solution ?
Code which i do currently.
For Example: If TTS is speaking this string: How are you! and when it reaches 'how', how can I display 'how' in text view only single word.
Initializations();
textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(MainActivity.this, "Sorry ! Language data missing", Toast.LENGTH_SHORT).show();
} else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "Sorry ! Language not supported", Toast.LENGTH_SHORT).show();
} else {
speek.setEnabled(true);
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(MainActivity.this, "Sorry ! Text to speech can't be initialized", Toast.LENGTH_SHORT).show();
speek.setEnabled(false);
}
}
});
speek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SpeekOut();
}
});
private void SpeekOut() {
String text = etTextToSpeech.getText().toString();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Try this to read
add this in any button click.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
Intent i = new Intent(MainService.ACTION);
if (isServiceRunning()) {
stopService(i);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
} else {
startService(i);
runAsForeground();
}
try { startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show();
}
//runAsForeground function here
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Night Mode")
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
To display in the textview
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
//MainService
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
public class MainService extends Service {
public static final String ACTION = "com.thul.CallRecorder.CALL_RECORD";
public static final String STATE = "STATE";
public static final String START = "START";
public static final String STORAGE = "STORAGE";
public static final String INCOMING = "INCOMING";
public static final String OUTGOING = "OUTGOING";
public static final String BEGIN = "BEGIN";
public static final String END = "END";
protected static final String TAG = MainService.class.getName();
protected static final boolean DEBUG = false;
private static final String AMR_DIR = "/callrec/";
private static final String IDLE = "";
private static final String INCOMING_CALL_SUFFIX = "_i";
private static final String OUTGOING_CALL_SUFFIX = "_o";
private Context cntx;
private volatile String fileNamePrefix = IDLE;
private volatile MediaRecorder recorder;
private volatile PowerManager.WakeLock wakeLock;
private volatile boolean isMounted = false;
private volatile boolean isInRecording = false;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.cntx = getApplicationContext();
this.prepareAmrDir();
log("service create");
}
#Override
public void onDestroy() {
log("service destory");
this.stopRecording();
this.cntx = null;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null == intent || !ACTION.equals(intent.getAction())) {
return super.onStartCommand(intent, flags, startId);
}
String state = intent.getStringExtra(STATE);
String phoneNo = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
log("state: " + state + " phoneNo: " + phoneNo);
if (OUTGOING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ OUTGOING_CALL_SUFFIX;
} else if (INCOMING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ INCOMING_CALL_SUFFIX;
} else if (BEGIN.equals(state)) {
startRecording();
} else if (END.equals(state)) {
stopRecording();
} else if (STORAGE.equals(state)) {
String mountState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(mountState)) {
prepareAmrDir();
} else {
isMounted = false;
}
if (!isInRecording) {
stopSelf();
}
}
return START_STICKY;
}
public Context getContext() {
return cntx;
}
private void stopRecording() {
if (isInRecording) {
isInRecording = false;
recorder.stop();
recorder.release();
recorder = null;
releaseWakeLock();
stopSelf();
log("call recording stopped");
}
}
private String getDateTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
Date now = new Date();
return sdf.format(now);
}
private String getMonthString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date now = new Date();
return sdf.format(now);
}
private String getDateString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
return sdf.format(now);
}
private String getTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date now = new Date();
return sdf.format(now);
}
private void startRecording() {
if (!isMounted)
return;
stopRecording();
try {
File amr = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ getDateTimeString()
+ "_"
+ fileNamePrefix + ".amr");
log("Prepare recording in " + amr.getAbsolutePath());
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(amr.getAbsolutePath());
recorder.prepare();
recorder.start();
isInRecording = true;
acquireWakeLock();
log("Recording in " + amr.getAbsolutePath());
} catch (Exception e) {
Log.w(TAG, e);
}
}
private void prepareAmrDir() {
isMounted = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isMounted)
return;
File amrRoot = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + AMR_DIR);
if (!amrRoot.isDirectory())
amrRoot.mkdir();
}
private String getContactName(Context cntx, String phoneNo) {
if (null == phoneNo)
return "";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
ContentResolver cr = cntx.getContentResolver();
Cursor c = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
null, null, null);
if (null == c) {
log("getContactName: The cursor was null when query phoneNo = "
+ phoneNo);
return phoneNo;
}
try {
if (c.moveToFirst()) {
String name = c.getString(0);
name = name.replaceAll("(\\||\\\\|\\?|\\*|<|:|\"|>)", "");
log("getContactName: phoneNo: " + phoneNo + " name: " + name);
return name;
} else {
log("getContactName: Contact name of phoneNo = " + phoneNo
+ " was not found.");
return phoneNo;
}
} finally {
c.close();
}
}
private void log(String info) {
if (DEBUG && isMounted) {
File log = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ "log_"
+ getMonthString()
+ ".txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(log,
true));
try {
synchronized (out) {
out.write(getDateString()+getTimeString());
out.write(" ");
out.write(info);
out.newLine();
}
} finally {
out.close();
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
private void acquireWakeLock() {
if (wakeLock == null) {
log("Acquiring wake lock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
log("Wake lock released");
}
}
}
//isServiceRunning
private boolean isServiceRunning() {
ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().equals(
MainService.class.getName())) {
return true;
}
}
return false;
}

Updating the UI upon receiving an android push notification

I have a query regarding android push notification and i had asked it in another stackoverflow post and i did not get much help out of it [Query regarding Android push notifications. So i am posting it again, and it is as follows:
I have an android app that receives push notifications from Google push notification service. When i tap on the received notification, it opens an UI which displays this message, it is a list view. Now, when the user receives the push notification, and assuming that this screen is open, the UI should be refreshed automatically, such that it displays the latest notification. Could anybody let me know how i can solve this?
Below is my code that i have implemented:
Java code to receive the notification:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import com.example.foodu.R;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCM ::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "53340195486";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
#Override
protected void onMessage(Context context, Intent data) {
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, com.example.foodu.Notification.class);
// Pass data to the new activity
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setWhen(System.currentTimeMillis())
.setContentTitle("Deals")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}
#Override
protected void onUnregistered(Context arg0, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
}
The code for the corresponding activity that would be launched when the user taps on the notification:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import com.example.foodu.R;
import com.example.foodu.R.drawable;
import com.example.foodu.R.id;
import com.example.foodu.R.layout;
import com.example.foodu.R.menu;
import com.google.android.gcm.GCMRegistrar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Notification extends ActionBarActivity {
LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>();
ListView listView = null;
NotificationListAdapter adaptor;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
listView = (ListView) findViewById(R.id.listView1);
// Retrive the data from GCMIntentService.java
Intent i = getIntent();
String message = i.getStringExtra("message");
//getDataForDisplay();
if(message!=null)
{
parseData(message);
}else{
getDataToDisplay();
}
adaptor = new NotificationListAdapter(getApplicationContext(), notificationList);
listView.setAdapter(adaptor);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText("No Events Yet!");
listView.setEmptyView(emptyText);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
onListitemSelect(position);
view.setSelected(true);
return true;
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
adaptor.notifyDataSetChanged();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
void writeToFile(){
FileOutputStream fos;
try {
fos = openFileOutput("varun", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(notificationList);
oos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void readFromFile(){
try{
FileInputStream fis = openFileInput("varun");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject();
ois.close();
for (int i = 0; i < local.size(); i++) {
notificationList.add(local.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getDataToDisplay() {
// TODO Auto-generated method stub
readFromFile();
}
private void parseData(String message) {
try {
int len = 0;
String[] stringArr = new String[100];
StringTokenizer st = new StringTokenizer(message, ".");
len = st.countTokens();
for (int i = 0; i < len; i++) {
if (st.hasMoreTokens()) {
stringArr[i] = st.nextToken();
}
}
NotificationData data = new NotificationData();
data.title = stringArr[0];
data.venue = stringArr[1];
data.date = stringArr[2];
data.time = stringArr[3];
notificationList.add(data);
readFromFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDateToDisplay() {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
writeToFile();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notificationmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_register){
registerDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
private void registerDevice() {
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar
.register(Notification.this, GCMIntentService.SENDER_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.notificationcontext, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_calender:
addToCalender();
mode.finish();
return true;
case R.id.menu_delete:
//deleteData();
showAlertBox();
return false;
case R.id.menu_share:
shareDate();
mode.finish();
return true;
case R.id.menu_copy:
copyToClip();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
adaptor.removeSelection();
}
};
void onListitemSelect(int position) {
adaptor.toggleSelection(position);
boolean hasCheckedItems = adaptor.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null) {
mActionMode = startActionMode((Callback) mActionModeCallback);
} else if (!hasCheckedItems && mActionMode != null) {
mActionMode.finish();
}
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount()));
}
protected void showAlertBox() {
// TODO Auto-generated method stub
AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this);
builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?");
builder1.setCancelable(true);
builder1.setIcon(R.drawable.alert);
builder1.setTitle("Caution");
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteData();
mActionMode.finish();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
protected void copyToClip() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Notification App", shareText);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Data copied to ClipBoard",
Toast.LENGTH_LONG).show();
}
protected void shareDate() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
String share = shareText.toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, share);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
protected void deleteData() {
int count = 0;
int startPoint = adaptor.getSelectedIds().keyAt(0);
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
adaptor.remove(notificationList.get(startPoint));
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message+" deleted", Toast.LENGTH_LONG)
.show();
}
private void addToCalender() {
try {
int count = 0;
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
ContentResolver cr = getApplicationContext()
.getContentResolver();
ContentValues values = new ContentValues();
String myDate = data.date + " " + data.time;
String timeArr[] = data.time.split("to");
SimpleDateFormat sfd = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault());
long time = sfd.parse(myDate).getTime();
values.put(CalendarContract.Events.DTSTART, time);
if (timeArr.length > 0) {
String endTime = timeArr[1];
SimpleDateFormat timeFormat = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy hh a", Locale.getDefault());
long endtime = timeFormat.parse(data.date + " " + endTime)
.getTime();
values.put(CalendarContract.Events.DTEND, endtime);
}
values.put(CalendarContract.Events.TITLE, data.title);
values.put(CalendarContract.Events.DESCRIPTION, data.venue);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE,
timeZone.getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr
.insert(CalendarContract.Events.CONTENT_URI, values);
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message + " added to Calender", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use LocalBroadcastManager
Check following code / steps
1) Add in your activity (UI refresh Activity)
private BroadcastReceiver mMyBroadcastReceiver;
Then ,
2) In onResume
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
Toast.makeText(getApplicationContext(), "Receiver", 2000).show();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action"));
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}}
// and your other code
3) Then unregister in onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4) Finally add in your GCM reciver class.
first check your activity is Visible or not using static variable
if visible add
Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec);
else
use Notification Manager for notification.
I think this is easy and best way to refresh your listview UI / call Fetching method.

how to display nfc tag?

When I read NFC tag Read an NFC tag message only will displayed. What did I miss? Is there a way to detect NFC ID?
I followed this tutorial.
package com.example.zmynfc;
import java.util.Arrays;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mIntentFilters;
private String[][] mNFCTechLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView)findViewById(R.id.textView1);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter != null) {
mTextView.setText("Read an NFC tag");
} else {
mTextView.setText("This phone is not NFC enabled.");
}
// create an intent with tag data and deliver to this activity
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// set an intent filter for all MIME data
IntentFilter ndefIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndefIntent.addDataType("*/*");
mIntentFilters = new IntentFilter[] { ndefIntent };
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}
mNFCTechLists = new String[][] { new String[] { NfcF.class.getName() } };
}
#Override
public void onNewIntent(Intent intent) {
String action = intent.getAction();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
String s = action + "\n\n" + tag.toString();
// parse through all NDEF messages and their records and pick text type only
Parcelable[] data = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (data != null) {
try {
for (int i = 0; i < data.length; i++) {
NdefRecord [] recs = ((NdefMessage)data[i]).getRecords();
for (int j = 0; j < recs.length; j++) {
if (recs[j].getTnf() == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(recs[j].getType(), NdefRecord.RTD_TEXT)) {
byte[] payload = recs[j].getPayload();
String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
int langCodeLen = payload[0] & 0077;
s += ("\n\nNdefMessage[" + i + "], NdefRecord[" + j + "]:\n\"" +
new String(payload, langCodeLen + 1, payload.length - langCodeLen - 1,
textEncoding) + "\"");
}
}
}
} catch (Exception e) {
Log.e("TagDispatch", e.toString());
}
}
mTextView.setText(s);
}
#Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null)
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mNFCTechLists);
}
#Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
}
Add this in your onCreate() method:
private NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
private PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
Then write this for intercept NFC id:
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
String rfid = byteToHex(id);
}
public String byteToHex(byte[] args) {
String risultato = "";
for (int i = 0; i < args.length; i++) {
risultato += Integer.toString((args[i] & 0xff) + 0x100,16).substring(1);
}
return risultato;
}
public void enableForegroundMode() {
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter[] writeTagFilters = new IntentFilter[] {tagDetected};
adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
public void disableForegroundMode() {
adapter.disableForegroundDispatch(this);
}
public void onResume() {
super .onResume();
enableForegroundMode();
}
public void onPause() {
super .onPause();
disableForegroundMode();
}

Inverting audio in Java

I am new to Java and I want to know how to invert audio (fixed voice inversion) coming from the input through a loopback to the output after a delay. How and where would I do this, and would I be able to set a frequency of the inversion somehow. Thanks.
package net.bitplane.android.microphone;
import java.nio.ByteBuffer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
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.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
public class MicrophoneService extends Service implements OnSharedPreferenceChangeListener {
private static final String APP_TAG = "Microphone";
private static final int mSampleRate = 44100;
private static final int mFormat = AudioFormat.ENCODING_PCM_16BIT;
private AudioTrack mAudioOutput;
private AudioRecord mAudioInput;
private int mInBufferSize;
private int mOutBufferSize;
SharedPreferences mSharedPreferences;
private static boolean mActive = false;
private NotificationManager mNotificationManager;
private MicrophoneReceiver mBroadcastReceiver;
private class MicrophoneReceiver extends BroadcastReceiver {
// Turn the mic off when things get loud
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
SharedPreferences prefs = context.getSharedPreferences(APP_TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefs.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(APP_TAG, "Creating mic service");
// notification service
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBroadcastReceiver = new MicrophoneReceiver();
// create input and output streams
mInBufferSize = AudioRecord.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mOutBufferSize = AudioTrack.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mAudioInput = new AudioRecord(MediaRecorder.AudioSource.MIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mInBufferSize);
mAudioOutput = new AudioTrack(AudioManager.STREAM_MUSIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mOutBufferSize, AudioTrack.MODE_STREAM);
// listen for preference changes
mSharedPreferences = getSharedPreferences(APP_TAG, MODE_PRIVATE);
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mActive = mSharedPreferences.getBoolean("active", false);
if (mActive)
record();
}
#Override
public void onDestroy() {
Log.d(APP_TAG, "Stopping mic service");
// close the service
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
// disable the listener
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
mAudioInput.release();
mAudioOutput.release();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(APP_TAG, "Service sent intent");
// if this is a stop request, cancel the recording
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals("net.bitplane.android.microphone.STOP")) {
Log.d(APP_TAG, "Cancelling recording via notification click");
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// intercept the preference change.
if (!key.equals("active"))
return;
boolean bActive = sharedPreferences.getBoolean("active", false);
Log.d(APP_TAG, "Mic state changing (from " + mActive + " to " + bActive + ")");
if (bActive != mActive) {
mActive = bActive;
if (mActive)
record();
if (!mActive)
mNotificationManager.cancel(0);
}
}
public void record() {
Thread t = new Thread() {
public void run() {
Context context = getApplicationContext();
CharSequence titleText = getString(R.string.mic_active);
CharSequence statusText = getString(R.string.cancel_mic);
long when = System.currentTimeMillis();
Intent cancelIntent = new Intent();
cancelIntent.setAction("net.bitplane.android.microphone.STOP");
cancelIntent.setData(Uri.parse("null://null"));
cancelIntent.setFlags(cancelIntent.getFlags() | Notification.FLAG_AUTO_CANCEL);
PendingIntent pendingCancelIntent = PendingIntent.getService(context, 0, cancelIntent, 0);
Notification notification = new Notification(R.drawable.status, titleText, when);
notification.setLatestEventInfo(context, titleText, statusText, pendingCancelIntent);
mNotificationManager.notify(0, notification);
// allow the
registerReceiver(mBroadcastReceiver, new IntentFilter(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Log.d(APP_TAG, "Entered record loop");
recordLoop();
Log.d(APP_TAG, "Record loop finished");
}
private void recordLoop() {
if ( mAudioOutput.getState() != AudioTrack.STATE_INITIALIZED || mAudioInput.getState() != AudioTrack.STATE_INITIALIZED) {
Log.d(APP_TAG, "Can't start. Race condition?");
}
else {
try {
try { mAudioOutput.play(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start playback"); return; }
try { mAudioInput.startRecording(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start recording"); mAudioOutput.stop(); return; }
try {
ByteBuffer bytes = ByteBuffer.allocateDirect(mInBufferSize);
int o = 0;
byte b[] = new byte[mInBufferSize];
while(mActive) {
o = mAudioInput.read(bytes, mInBufferSize);
bytes.get(b);
bytes.rewind();
mAudioOutput.write(b, 0, o);
}
Log.d(APP_TAG, "Finished recording");
}
catch (Exception e) {
Log.d(APP_TAG, "Error while recording, aborting.");
}
try { mAudioOutput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop playback"); mAudioInput.stop(); return; }
try { mAudioInput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop recording"); return; }
}
catch (Exception e) {
Log.d(APP_TAG, "Error somewhere in record loop.");
}
}
// cancel notification and receiver
mNotificationManager.cancel(0);
try {
unregisterReceiver(mBroadcastReceiver);
} catch (IllegalArgumentException e) { Log.e(APP_TAG, "Receiver wasn't registered: " + e.toString()); }
}
};
t.start();
}
}

Categories