How to activate silent mode on Android device - java

ArrayList prayerTimes = prayers.getPrayerTimes(cal, latitude,longitude,timezone);
ArrayList prayerNames = prayers.getTimeNames();
for (int i = 0; i < prayerTimes.size(); i++) {
txtPrayerTimes.append("\n" + prayerNames.get(i) + " - "+ prayerTimes.get(i));
Screenshot of output to this point
Now I want to activate silent mode if current time = fajr time i.e 03:48 AM
My code so far, which I'm sure is crap...
if(getReminingTime()== prayerTimes.get(0)) {
Toast.makeText(getApplicationContext(), "Peace mode activated",Toast.LENGTH_SHORT).show();
AudioManager audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}}}
private String getReminingTime(){
String delegate = "hh:mm aaa";
return (String) DateFormat.format(delegate,Calendar.getInstance().getTime());}
What is the correct way to enable silent mode on the device?

Related

Bluetooth module JDY-08 not finding Android device

I have 1 JDY-08 MASTER that scans looking for myDeviceName and triggers a function when it finds that device name.
String get_ble_scan_data(void){
String final_result = "";
String result = "";//reset and declare
String extract = set_ble("AT+SCAN1");//scan for device name, signal strength and mac address
String extract2 = set_ble("AT+GETDCD");//get number of device found
//now we are going to check for which extraction has the data we interested in
if((extract.length() > threshold or extract.length() > threshold)){
result = extract;//pass extract as result
if(extract2.length() > extract.length()){//check which is bigger
result = extract2;//pass extract2 as result if its bigger in length than extract
}
}
if(result.length() > 0){//add filter and execution here
String filter = result;//copy
result = "";// reset
while(filter.indexOf('=') > -1){// we use the char = as a seperator
filter = filter.substring(filter.indexOf('=') + 1);//remove strings before seperator
result += filter.substring(0, filter.indexOf('\n')) + ' '; //extract till newline character
filter = filter.substring(filter.indexOf(result) + result.length());//remove extracted result so we go on to next extraction of same result if there is more device picked up
detect
}
result.trim();//remove spaces at the end or start if any
final_result = result;
}
return final_result;
}
void ble_response(String search_result){
String scan_result = search_result;//do bluetooth scan
if(scan_result.indexOf(myDeviceName) > -1 ){//when data present in scan and it contains desired key
if(scan_result.indexOf(' ') == -1){//if only one ble is picked up
ble_macaddress = scan_result.substring(0, scan_result.indexOf(','));
scan_result = scan_result.substring(scan_result.indexOf(ble_macaddress) + 1 + ble_macaddress.length(), scan_result.length());//remove mac address
ble_strength = scan_result.substring(0, scan_result.indexOf(','));
ble_name = scan_result.substring(scan_result.indexOf(ble_strength) + 1 + ble_strength.length(), scan_result.length());//remove mac address
if(((int) ble_strength.toFloat()) >= trigger_threshold and ble_name == key){
trigger_action();
}
}else{//if multiple ble is picked up
String cut = "";
while(scan_result.indexOf(',') > -1){//while there is still result to be processed
cut = scan_result.substring(0, scan_result.indexOf(' '));
scan_result = scan_result.substring(scan_result.indexOf(cut) + 1 + cut.length(), scan_result.length());
if(cut.indexOf(myDeviceName) > -1){//only analyze if it contains key
ble_macaddress = cut.substring(0, cut.indexOf(','));
cut = cut.substring(cut.indexOf(ble_macaddress) + 1 + ble_macaddress.length(), cut.length());//remove mac address
ble_strength = cut.substring(0, cut.indexOf(','));
ble_name = cut.substring(cut.indexOf(ble_strength) + 1 + ble_strength.length(), cut.length());//remove mac address
if(((int) ble_strength.toFloat()) >= trigger_threshold and ble_name == key){
trigger_action();
break;
}
}
}
}
}
If I use another JDY-08 device with one button, It finds the device and triggers the action:
if(!digitalRead(11)){//if button is pushed///////
delay(500);
set_ble("AT+NAMEmyDeviceName");//change ble name
while(!digitalRead(11));//do nothing while button is still pressed
delay(2000);//allow time before name change back
set_ble("AT+NAMEJDY-08");//change name back
But when I use the phone It doesn´t trigger the action:
private void advertise(){
final BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
final AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
.setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
.setConnectable( true )
.build();
final AdvertiseData data = new AdvertiseData.Builder()
.setIncludeDeviceName( true )
.build();
final AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
#Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
}
#Override
public void onStartFailure(int errorCode) {
Log.e( "BLE", "Advertising onStartFailure: " + errorCode );
super.onStartFailure(errorCode);
}
};
advertiser.startAdvertising(settings,data,advertisingCallback);
final Handler myTimerHandler = new Handler();
myTimerHandler.postDelayed(
new Runnable()
{
#Override
public void run(){
advertiser.stopAdvertising(advertisingCallback);
}
} , 30000);
}
I also use the intent with BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE.
Using NRFConnect app, I can see how the JDY-08 Button device changes the device name (That triggers the action on the JDY-08 MASTER). I can also see the Android device with myDeviceName but this does not trigger the action. Am I missing something in the Android app?
The problem was that the JDY-Master only received the name of JDY devices. All other devices show mac address and signal strength only.

Extracting .pst file to msg but not getting exact number of msg file

I am trying to extract pst file into msg.
I am using aspose jar. I share my code where we get exact number of file in each subfolder.
public static void displayFolderAndMessageInformationForPSTFile(String dataDir) {
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(dataDir + "allen.pst");
// Get the folders information
FolderInfoCollection folderInfoCollection = pst.getRootFolder().getSubFolders();
// Browse through each folder to display folder name and number of messages
for (int i = 0; i < folderInfoCollection.size(); i++) {
FolderInfo folderInfo = (FolderInfo) folderInfoCollection.get_Item(i);
System.out.println("FolderId: " + folderInfo.getEntryIdString());
System.out.println("Folder: " + folderInfo.getDisplayName());
System.out.println("Total items: " + folderInfo.getContentCount());
System.out.println("Total unread items: " + folderInfo.getContentUnreadCount());
System.out.println("-----------------------------------");
}
}
FolderId: AAAAAJJu05VTxVRJlC5mJefQvVeCgAAA
Folder: Inbox
Total items: 66
Total unread items: 0
But when extract message content then i get different number of msg. It give only 49 msg in inbox folder.
The following below code:
public static void main(String[] args) {
String pstFileName = dataDir + "allen.pst";
// Load the Outlook PST file
PersonalStorage pst = PersonalStorage.fromFile(pstFileName);
// Get the folders and messages information
FolderInfo folderInfo = pst.getRootFolder();
// Create a folder for this PST
String strRootFolderName = "allen.pst".replace(".pst", "") + ".Java";
new File(dataDir + strRootFolderName).mkdir();
// Call the recursive method to extract msg files from each folder
extractMsgFiles(folderInfo, pst, dataDir + strRootFolderName);
}
private static void extractMsgFiles(FolderInfo folderInfo, PersonalStorage pst, String strPSTFile) {
// Display the folder name
System.out.println("Folder: " + folderInfo.getDisplayName());
// Create folder to store the messages
String folderName = strPSTFile + "\\" + folderInfo.getDisplayName();
new File(folderName).mkdir();
// Loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.getContents();
for (int i = 0; i < messageInfoCollection.size(); i++) {
MessageInfo messageInfo = (MessageInfo) messageInfoCollection.get_Item(i);
System.out.println("Saving message " + messageInfo.getSubject() + "....");
// Get the message in MapiMessage instance
MapiMessage message = pst.extractMessage(messageInfo);
// Delete special characters which are invalid to use as windows file name
String messageName = null;
if (message.getSubject() == null || message.getSubject().isEmpty() == true) {
messageName = getRidOfIllegalFileNameCharacters(messageInfo.getEntryIdString());
} else {
messageName = getRidOfIllegalFileNameCharacters(message.getSubject());
}
// Save this message to disk in MSG format
message.save(folderName + "\\" + messageName + ".msg");
}
// Call this method recursively for each subfolder
if (folderInfo.hasSubFolders() == true) {
for (int i = 0; i < folderInfo.getSubFolders().size(); i++) {
FolderInfo subfolderInfo = (FolderInfo) folderInfo.getSubFolders().get_Item(i);
extractMsgFiles(subfolderInfo, pst, strPSTFile);
}
}
}
Help me... Where did i make mistake ? I am new in Aspose.
Please have a look at the following code snippet for extracting message files. You may use this method in place of your extractMsgFiles method.
private static void ExtractMsgFiles(FolderInfo folderInfo, PersonalStorage pst)
{
// display the folder name
Console.WriteLine("Folder: " + folderInfo.DisplayName);
Console.WriteLine("==================================");
// loop through all the messages in this folder
MessageInfoCollection messageInfoCollection = folderInfo.GetContents();
foreach (MessageInfo messageInfo in messageInfoCollection)
{
Console.WriteLine("Saving message {0} ....", messageInfo.Subject);
// get the message in MapiMessage instance
MapiMessage message = pst.ExtractMessage(messageInfo);
// save this message to disk in msg format
message.Save(message.Subject.Replace(":", " ") + ".msg");
// save this message to stream in msg format
MemoryStream messageStream = new MemoryStream();
message.Save(messageStream);
}
// Call this method recursively for each subfolder
if (folderInfo.HasSubFolders == true)
{
foreach (FolderInfo subfolderInfo in folderInfo.GetSubFolders())
{
ExtractMsgFiles(subfolderInfo, pst);
}
}
}
You may visit the link Working with Messages in a PST File in case you are interested in more details.
I work with Aspose as Developer evangelist.
The emails not having unique subject names could be causing this issue? I had this exact issue when doing something similar in Powershell. Putting an autonumber in the filename could help get around this.

Android using SharedPreferences

I found out a common way to store data is Android's SharedPreferences. So I went out and tried to implement it with my application.
What I want to do:
My application retrieves weather details from the users current location, if the user desires he/she can add the location by pressing add to favorites. They can have up to 10 favorite locations. So I want to store the location description (exp: Dayton, OH), the latitude and longitude (So I may fetch the details when they want to see that weather). So Shared Preferences seem to fit my need.
What I did:
- I created a loop that would cycle through 10 keys (for 10 locations) an as long as the keys were null the location information would be saved. If the key was not null, it means the key has already been created.
My code:
public void writeNewLocation(String stringLat, String stringLon, String location) {
this.latitude = stringLat;
this.longitude = stringLon;
this.location = location;
pref = mContext.getSharedPreferences("favoritelocations", 0); // 0 - for private mode
Editor editor = pref.edit();
//Loop through all the favorite keys to find an open spot:
for(int i = 1; i <= 10; i++) {
//Test for current favorite key:
String value = pref.getString("favorite"+ i +"_location",null);
if (value == null) {
//The key does not exist so it can be created and written to:
//First write the location description:
editor.putString("favorite" + i + "_location", location);
//Next the write the latitude and lonitude values:
editor.putString("favorite" + i + "_latitude", latitude);
editor.putString("favorite" + i + "_longitude", longitude);
editor.commit();
i = 11;
} else {
//If at end of loop; Inform user:
if(i == 10) {
//Display an error:
//Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//Create the AlertDialog characteristics:
builder.setMessage("You can only have up to 10 favorite locations. Delete some to make room.");
builder.setTitle("Message");
//Show the AlertDialog:
msgDialog = builder.create();
editor.commit();
i = 11;
} else {
//Back to top of loop.
}
}
}
//Commit to changes:
editor.commit(); // commit changes
}
So I loop through ten possible keys, if it hits 10, and all spots are taken, I alert the user. But when I call this method to create a favorite location, then call 1 of the 10 getters to display the information that should've been saved, I get a null. :( Is it too early in the morning over here or am I doing something wrong...
Thanks c:

What is wrong with my ContentProvider in Android 4.3?

My app works just fine with any Android version before 4.3. I mean when I input a word into edWord (EditText field), a list of similarly-spelled words will appear in the list view.
But in Android 4.3, it always returns null, claiming that app_ContentProvider cannot find the supported uri.
I use the following code to show the word list:
public void showWordlist() {
edWord.setEnabled(true);
String word = edWord.getText().toString();
Uri uri = Uri.parse("content://doyle.app_name.app_ContentProvider/dict/" + mDBFile.fileName + "/list/" + word);
edWord.requestFocus();
try
{
Cursor result = getContentResolver().query(uri,null,null,null,null);
Log.i(MAIN_TAG, "Found word = " + result);
//I think the problem lies somewhere here because
//the 'result' is always 'null' (see the above log.i)
if (result != null)
{
int countRow=result.getCount();
Log.i(MAIN_TAG, "countRow = " + countRow);
mLSTCurrentWord.clear();
//mLSTCurrentContent.clear();
mLSTCurrentWordId.clear();
mAdapter.clear();
if (countRow >= 1)
{
int indexWordColumn = result.getColumnIndex("word");
int indexIdColumn = result.getColumnIndex("id");
result.moveToFirst();
String strWord;
int intId;
int i = 0;
do
{
strWord = Utility.decodeContent(result.getString(indexWordColumn));
intId = result.getInt(indexIdColumn);
mLSTCurrentWord.add(i,strWord);
mLSTCurrentWordId.add(i,intId);
//mLSTCurrentContent.add(i,strContent);
mAdapter.add(strWord);
i++;
} while (result.moveToNext());
}
result.close();
}
lstWord.setAdapter(mAdapter);
}
catch (Exception ex)
{
Log.e(MAIN_TAG, "Error = " + ex.toString());
}
edWord.setEnabled(true);
}
And here is my app_ContentProvider.
I have no idea whether there are any changes in Android 4.3 that stop my app from functioning normally.
Regarding my code lines above, can you please tell me what the problem might be? Thanks a lot.
Try set the property android:exported="true" for your content provider in your Manifest. It seems that the default value of this property has changed in android 4.3

Null values on reading custom JAD attributes

I have a blackberry Application. It is downloaded from a web page which provides dynamic JAD file content. The JSP prints those :
out.println("Appid: " + appid);
out.println("Ip: " + user.getIp());
out.println("Servicename: " + service);
out.println("MIDlet-Version: 1.0.0");
out.println("MIDlet-Jar-URL: MyApp.jar");
out.println("MIDlet-Jar-Size: 91633");
out.println("MicroEdition-Profile: MIDP-2.0");
(and other attributes goes on like that..)
I need to get my custom attributes like "Appid" but it sometimes gets null values. User can download and run the app, but some of them cannot get my custom attributes. I dont know it is about the phone model or the current state of OS, but according to my logs, this problem appears mostly on those devices :
9800 with OS 6.0.0.546
9300 with OS 6.0.0.570
9300 with OS 6.0.0.668
9320 with OS 7.1.0.398
My code to get attributes :
CodeModuleGroup cmg = null;
CodeModuleGroup[] allGroups = CodeModuleGroupManager.loadAll();
String moduleName = ApplicationDescriptor
.currentApplicationDescriptor().getModuleName();
for (int i = 0; i < allGroups.length; i++) {
if (allGroups[i].containsModule(moduleName)) {
cmg = allGroups[i];
break;
}
}
if (cmg != null) {
AppData.firstPageURL = cmg.getProperty("Firstpage");
AppData.appId = cmg.getProperty("Appid");
AppData.firstIp = cmg.getProperty("Ip");
AppData.firstSubServiceName = cmg.getProperty("Servicename");
for (Enumeration e = cmg.getPropertyNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
String value = cmg.getProperty(name);
AppData.errorStep += "-" + name + ":" + value + "-";
}
}
By the way, I determined that the code in the for loop above never runs in these cases.
Any idea ?
Sometimes, ApplicationDescriptor.currentApplicationDescriptor().getModuleName() gives the name of the sibling cod file instead of the main cod file. So, if your module name is MyApp, the function may return MyApp-1.
To solve this, you have to strip out the number after the hyphen.
String moduleName = ApplicationDescriptor.currentApplicationDescriptor()
.getModuleName();
if(moduleName.indexOf('-') > 0) {
moduleName = moduleName.substring(0, moduleName.indexOf('-');
}

Categories

Resources