The alarmmanager is working perfectly on emulator but not on physical device.
It works sometimes on the device. Please help. i cant find why its not working on device. Is there a bug?
The same code was working fine earlier.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wim.wimonandroid"
android:versionCode="94"
android:versionName="10.1" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<application
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:screenOrientation="portrait"
android:name=".wimOnAndroid"
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=".Compas"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".TutorialZoomActivity1"
android:label="#string/ramadan" >
</activity>
<activity
android:name=".AlarmListView"
android:label="#string/app_name3" >
</activity>
<activity
android:name=".wimRss"
android:label="#string/app_name1" >
</activity>
<activity
android:name=".CityListView"
android:label="#string/app_name4" >
</activity>
<activity
android:name=".jummah"
android:label="#string/jummah" >
</activity>
<activity
android:name=".settings"
android:label="#string/settings" >
</activity>
<activity
android:name=".QA"
android:label="#string/QA" >
</activity>
<activity
android:name=".SendEmailActivity"
android:label="#string/app_name_Sendmail" >
</activity>
<activity
android:name=".Touch"
android:label="#string/app_name" >
</activity>
<activity
android:name=".compass"
android:label="#string/compass" >
</activity>
<activity
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name=".sehri"
android:label="sehri" >
</activity>
<activity
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden"
android:name=".iftari"
android:label="iftari" >
</activity>
<activity
android:name=".felles"
android:label="felles" >
</activity>
<!-- <service android:enabled="true" android:name=".AlarmService" /> -->
<service android:name=".MyAlarmService" >
</service>
<service android:name=".UpdateWidgetService" >
</service>
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".MyBroadcastreceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<data android:scheme="package" />
</intent-filter>
</receiver>
<receiver
android:name=".wimWidget"
android:label="#string/app_nameWid" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/hello_widget_provider" />
</receiver>
<activity
android:name=".SehriActivity"
android:label="#string/title_activity_sehri" >
</activity>
</application>
package com.wim.wimonandroid;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
public class MyAlarmService extends Service {
MediaPlayer player;
String readString = new String("");
String readAlarm = new String("");
String readSpilt = new String("");
String readForste = new String("");
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
#Override
public void onCreate() {
Log.v("tid", "MyAlarmService - onCreate()" );
try {
readFile(); //sjekker om Alarm er slått på eller ei
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
hent(); //setter neste alarm
} catch (IOException e) {
e.printStackTrace();
}
if(readString.equals("2") ){
Log.v("tid", "MyAlarmService - onCreate - Kaller onDestroy()" );
onDestroy() ;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v("tid", "MyAlarmService - onDestroy");
//writeFile(2);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("tid", "MyAlarmService - onStartCommand()");
String forste = new String("");
try {
readFile(); // Sjekker om alarm er på eller ei.
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
forste = readForste();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY) ; //1300
int minutes = cal.get(Calendar.MINUTE);
Log.v("tid", "MyAlarmService - onStartCommand - readAlarm: " +
readAlarm);
AudioManager am =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (am.getRingerMode()) {
case AudioManager.RINGER_MODE_SILENT:
Log.v("tid","Silent mode");
break;
case AudioManager.RINGER_MODE_VIBRATE:
Log.v("tid","Vibrate mode");
break;
case AudioManager.RINGER_MODE_NORMAL:
Log.v("tid","Normal mode - onStart");
// if(Integer.parseInt(readAlarm.trim()) == 0){
if(readAlarm.equals("0")){
Log.i("tid","Normal mode - door - Minutter: " + minutter);
am.setStreamVolume(AudioManager.STREAM_MUSIC,
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
player = MediaPlayer.create(this, R.raw.door);
player.setLooping(false); // Set looping
player.setVolume(1, 1);
player.start();
player.release();
Runnable r = new Runnable() {
public void run(){
}
};
Handler h = new Handler();
h.postDelayed(r, 60000);
//alarmHjelp.restart();
}
//else if(Integer.parseInt(readAlarm.trim()) == 1){
else if(readAlarm.equals("1")){
Log.i("tid","Normal mode - azaan");
am.setStreamVolume(AudioManager.STREAM_MUSIC,
am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
AudioManager.FLAG_SHOW_UI);
player = MediaPlayer.create(this, R.raw.azan);
player.setLooping(false); // Set looping
player.setVolume(1, 1);
player.start();
player.release();
Runnable r = new Runnable() {
public void run(){
}
};
Handler h = new Handler();
h.postDelayed(r, 60000);
}
break;
}
if(readAlarm.equals("0") || readAlarm.equals("1")){
Log.i("tid","vibrasjon");
Vibrator v = (Vibrator)
getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(4000);
Toast.makeText(getApplicationContext(), "Tid for bønn..." ,
Toast.LENGTH_LONG).show();
}
}
try {
hent(); //setter neste alarm
} catch (IOException e) {
e.printStackTrace();
}
//} // 2 er lydløs
Log.v("tid","MyAlarmService - OnStartCommand - Start sticky");
return START_STICKY;
}
public void hent() throws IOException{
Log.v("tid", "MyAlarmService - hent()");
int alarmH = 0;
int alarmM = 0;
Calendar cal2 = Calendar.getInstance();
int hour = cal2.get(Calendar.HOUR_OF_DAY) ;
int minutes = cal2.get(Calendar.MINUTE);
try {
checkBy = readCity();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tider = new String("");
Log.v("tid", "MyAlarmService - hent() - By: " + checkBy);
//Setting alarm every second hour
alarmH = alarmH + 2;
Intent myIntent = new Intent(this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
if(nesteDag == 1)
{
Log.v("tid", "MyAlarmService - hent() - nestedag");
cal.add( Calendar.DATE, 1 );
}
cal.set(Calendar.HOUR_OF_DAY, alarmH);
cal.set(Calendar.MINUTE, alarmM);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
Log.i("tid", "MyAlarmService - hent() - Neste alarm: " + alarmH +
":" + alarmM);
}
}
public void readFile() throws IOException{
Log.v("tid", "MyAlarmService - readFile() - readAlarm: " + readAlarm);
// open the file for reading
InputStream instream = openFileInput("alarm.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while (( readAlarm = buffreader.readLine()) != null) {
Log.v("tid", "readAlarm: " + readAlarm);
break;
}
instream.close();
if(readAlarm == null){
Log.v("tid", "MyAlarmService - readFile - readAlarm er NULL");
readAlarm = "2";
writeFile(2);
Log.v("tid", "MyAlarmService - readFile - readAlarm (ny verdi):
" + readAlarm);
}
}
public void onBackPressed()
{
this.startActivity(new Intent(this,wimOnAndroid.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
}
Related
I create a app which uses accessibility. I passed intent for android accessibility settings but its not executed.
Here is code of android manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.new_app">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/safety"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Service_Running" />
<activity android:name=".MainActivity" />
<activity android:name=".injured_activity" />
<activity android:name=".splash_Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Whatsapp_Accessibility"
android:label="Accessibility Service"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/whatsapp_service"/>
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService"/>
</intent-filter>
</service>
<service
android:name=".Background_Service"
android:enabled="true"
android:exported="true" />
</application>
</manifest>
Here is code of accessiblity service xml file
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowContentChanged"
android:packageNames="com.whatsapp"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100"
android:canRetrieveWindowContent="true"/>
Here is the code of activity in which intent is passed
package com.example.new_app;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.app.UiAutomation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;
public class splash_Activity extends AppCompatActivity {
SharedPreferences sharedPreferences;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_);
sharedPreferences= getSharedPreferences("MySharedPreferences",MODE_PRIVATE);
String phone=sharedPreferences.getString("Phone_Number","");
String message=sharedPreferences.getString("Message","");
if (!isAccessibilitySettingsOn(getApplicationContext())) {
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
if(phone!="" && message!="")
{
if(!isMyServiceRunning(Background_Service.class))
{
startForegroundService(new Intent(this,Background_Service.class));
}
Intent intent1=new Intent(this,Service_Running.class);
startActivity(intent1);
}
else
{
Intent intent1=new Intent(this,MainActivity.class);
startActivity(intent1);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + Whatsapp_Accessibility.class.getCanonicalName();
try {
accessibilityEnabled = Settings.Secure.getInt(
mContext.getApplicationContext().getContentResolver(),
android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
Log.v("this", "accessibilityEnabled = " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
Log.e("this", "Error finding setting, default accessibility to not found: "
+ e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
Log.v("this", "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
Log.v("this", "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
Log.v("this", "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
Log.v("this", "***ACCESSIBILITY IS DISABLED***");
}
return false;
}
}
Here is the code of Accessiblity Service
package com.example.new_app;
import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import java.util.List;
public class Whatsapp_Accessibility extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if(getRootInActiveWindow() == null){
return;
}
AccessibilityNodeInfoCompat rootNodeInfo = AccessibilityNodeInfoCompat.wrap(getRootInActiveWindow());
//get edit text if message from whats app
List<AccessibilityNodeInfoCompat> messageNodeList = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.whatsapp:id/entry");
if(messageNodeList == null || messageNodeList.isEmpty())
return;
//checking if message field if filled with text and ending with our suffix
AccessibilityNodeInfoCompat messageField = messageNodeList.get(0);
if(messageField == null || messageField.getText().length() == 0 || !messageField.getText().toString().endsWith(" Send by Safety App"))
return;
// get whatsapp send message button node list
List<AccessibilityNodeInfoCompat> sendMessageNodeList = rootNodeInfo.findAccessibilityNodeInfosByViewId("com.whatsapp:id/send");
if(sendMessageNodeList == null || sendMessageNodeList.isEmpty())
return;
AccessibilityNodeInfoCompat sendMessage = sendMessageNodeList.get(0);
if(!sendMessage.isVisibleToUser())
return;
//fire send button
sendMessage.performAction(AccessibilityNodeInfo.ACTION_CLICK);
try{
Thread.sleep(2000);
performGlobalAction(GLOBAL_ACTION_BACK);
Thread.sleep(2000);
performGlobalAction(GLOBAL_ACTION_BACK);
}catch (InterruptedException ignored) {}
}
#Override
public void onInterrupt() {
}
}
I tested all this code on android 10
hey i have service its wallpaper service (not live wallpaper) so when I enter the app i have 5 radio buttons every button decide the time that the wallpaper changes and I have a button that triggers the service and i got response from my server even when i close the app but.... when i restart the device i get 1 response only and the wallpaper not changing lets say i was choised for every 4 second to change just when i reboot it stops and like i said i receive just one response from my server and stops even the wallpaper don't change with this response take a look at my code you will understand more (I used receiver and boot primission but ... );
MainActivity;
private final static int INTERVAL = 4000; //10 min
private final static int INTERVAL2 = 1000*60*30; // 30 min
private final static int INTERVAL3 = 1000 * 60 * 120; // 2 hours
private final static int INTERVAL4 = 1000 * 60 * 360; // 6 hours min
private final static int INTERVAL5 = 1000 * 60 * 1440; // 1 day
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rd1 = (RadioButton) findViewById(R.id.radioButton);
rd2 = (RadioButton) findViewById(R.id.radioButton2);
rd3 = (RadioButton) findViewById(R.id.radioButton3);
rd4 = (RadioButton) findViewById(R.id.radioButton4);
rd5 = (RadioButton) findViewById(R.id.radioButton5);
radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
mHandler = new Handler();
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this , WallService.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
if (rd1.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL, pintent);
} else if (rd2.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL2, pintent);
}else if (rd3.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL3, pintent);
}else if (rd4.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL4, pintent);
}else if (rd5.isChecked()) {
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL5, pintent);
}
}
});
}
service
String forecastJsonStr;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
final Thread thread1 = new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("yay.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
DataOutputStream wr = new DataOutputStream(
urlConnection.getOutputStream());
wr.write("method=get_random_wallpaper".getBytes());
wr.flush();
wr.close();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("hey", buffer.toString());
}
if (buffer.length() == 0) {
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
}
});
thread1.start();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap result = Picasso.with(getBaseContext())
.load(hostName + hostWallpaperName + forecastJsonStr)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
thread.start();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
receiver
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, WallService.class);
context.startService(pushIntent);
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.lol8">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".BootCompletedIntentReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".WallService"
android:enabled="true"
android:exported="true">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After device reboot alarms set in Alarm manager are cleared - docs
You need to initialize Alarm manager again in your on BOOT_COMPLETED receiver. You can use sharedPrefference to store the time you need to set your alarms
In onClick of the activity add
SharedPreference preference = PreferenceManager.getDefaultSharedPreference(this);
preference.edit.putInt("timeInterval",INTERVAL).apply;
Then in onReceive in the receiver:
SharedPreference preference =
PreferenceManager.getDefaultSharedPreference(this);
int interval = preference.getInt("timeInterval", 4000);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),interval, pintent);
Create a receiver and register like this in manifest, then onReceive() you need to start your service again
<receiver
android:enabled="true"
android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
I created application that if the button is click it will send SMS to the number that came from webservice. Then I use Alarm Manager to send SMS repeatedly in the number that i get from the web service. It is working fine but when I change the number that I want to send an SMS it will not work. I don't know what is wrong with my code. Here is my code.
This is my code that send an SMS.
public class EmergencyAssistance extends ActionBarActivity {
ArrayList<Objects> objectsList = new ArrayList<>();
String url = "http://192.168.254.108:8080/taxisafe3/webService/listcontact";
String urls = "http://192.168.254.108:8080/taxisafe3/webService/plate";
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String message;
String message1;
Button send;
LocationService locationService;
double lat;
double lng;
StringBuilder address;
StringBuffer smsBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_assistance);
send = (Button) findViewById(R.id.emergency);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setData();
new Task().execute(urls);
new Tasks().execute(url);
}
});
}
public class Task extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setCon1(jsonobject.getString("con1"));
objects.setCon2(jsonobject.getString("con2"));
objects.setCon3(jsonobject.getString("con3"));
objects.setCon4(jsonobject.getString("con4"));
objects.setCon5(jsonobject.getString("con5"));
objectsList.add(objects);
contact1 = objects.getCon1();
contact2 = objects.getCon2();
contact3 = objects.getCon3();
contact4 = objects.getCon4();
contact5 = objects.getCon5();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Tasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(urls);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setTaxi_plate_no(jsonobject.getString("taxi_plate_no"));
objects.setDriver_operator(jsonobject.getString("driver_operator"));
objectsList.add(objects);
message = objects.getTaxi_plate_no();
message1 = objects.getDriver_operator();
emergency();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void emergency() {
smsBody = new StringBuffer();
smsBody.append("https://maps.google.com/maps?q=");
smsBody.append(lat);
smsBody.append(",");
smsBody.append(lng);
String msgs = "[EMERGENCY!] \nTaxi plate #: " + message + "\nTaxi operator: " + message1 + "\n" + address + smsBody.toString();
try {
if (PatternChecker.isNotNull(contact1)) {
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(EmergencyAssistance.this, AlarmReceiver.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num1", contact1);
bundle.putCharSequence("msg1", msgs);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(EmergencyAssistance.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);
Toast.makeText(getApplicationContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "No Number", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
public void setData() {
locationService = new LocationService(getApplication());
if(locationService.canGetLocation()){
lat = locationService.getLatitude();
lng = locationService.getLongitude();
}else{
locationService.showSettingsAlert();
}
getMyLocationAddress();
}
public void getMyLocationAddress() {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
address = new StringBuilder();
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
address.append(fetchedAddress.getAddressLine(i)).append("\n");
}
} else
Toast.makeText(getApplicationContext(),"No Address", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
This is my Alarm Receiver.
public class AlarmReceiver extends BroadcastReceiver
{
String msg;
String num;
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
num = bundle.getString("num1");
msg = bundle.getString("msg1");
//Toast.makeText(context, num + msg, Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(num, null, msg, null, null);
}
}
This is my manifest to allow sending SMS and to register the alarm receiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.group.taxisafe" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<permission
android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/taxisafe"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Login"
android:label="TaxiSafe" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name=".DriverDetails"
android:label="#string/title_activity_driver_details" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".Contacts"
android:label="#string/title_activity_contacts" >
</activity>
<activity
android:name=".ReportActivity"
android:label="#string/title_activity_report" >
</activity>
<activity
android:name=".DriversList"
android:label="#string/title_activity_drivers_list" >
</activity>
<activity
android:name=".DriverAdapter"
android:label="#string/title_activity_driver_adapter" >
</activity>
<activity
android:name=".EmergencyAssistance"
android:label="#string/title_activity_emergency_assistance" >
</activity>
<activity
android:name=".DisplayContact"
android:label="#string/title_activity_display_contact" >
</activity>
<activity
android:name=".ContactAdapter"
android:label="#string/title_activity_contact_adapter" >
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
In my android app i am using Latest Geoloqi API to implement Geofence concept.when user entered into some region he has notify, for that purpose i am using Push Notifications.in GeoReceiver class three callback methods are calling but not onPushMessageReceived().please help me how to do it?
I am creating trigger with current location is it required to enter into region manually or since i am already in the location its not calling?
Note:I ve given required credentials in assets/geoloqi.properties file.when app is launched in logcat "Successfully registered for the C2DM service" msg also displayed.my code:
GeoloqiExampleActivity.java
public class GeoloqiExampleActivity extends Activity{
String TAG = "Geoloqi Example";
private LQService mService;
private boolean mBound;
GeoReceiver geoReceiver = new GeoReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, LQService.class);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
// Bind to the tracking service so we can call public methods on it
Intent intent = new Intent(this, LQService.class);
bindService(intent, mConnection, 0);
// Wire up the sample location receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(GeoReceiver.ACTION_LOCATION_CHANGED);
filter.addAction(GeoReceiver.ACTION_TRACKER_PROFILE_CHANGED);
filter.addAction(GeoReceiver.ACTION_LOCATION_UPLOADED);
filter.addAction(GeoReceiver.ACTION_PUSH_MESSAGE_RECEIVED);
registerReceiver(geoReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
// Unbind from LQService
if (mBound) {
unbindService(mConnection);
mBound = false;
}
// Unregister our location receiver
unregisterReceiver(geoReceiver);
}
public void sendRequest() {
// Performing a Trigger POST request
if (mService != null) {
LQSession session = mService.getSession();
LQTracker tracker = mService.getTracker();
tracker.setSession(session);
// Build your request
JSONObject trigger = new JSONObject();
try {
trigger.put("text", "Popcornapps");
trigger.put("type", "message");
trigger.put("latitude", 17.42557068);
trigger.put("longitude", 78.42022822);
trigger.put("radius", 500);
trigger.put("place_name", "Banjara Hills");
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
// Send the request
session.runPostRequest("trigger/create", trigger, new OnRunApiRequestListener() {
#Override
public void onSuccess(LQSession session, HttpResponse response) {
Toast.makeText(GeoloqiExampleActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
String result = s.toString().trim();
Log.d("On success Result", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(LQSession session, LQException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(GeoloqiExampleActivity.this, "Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(LQSession session, HttpResponse response, StatusLine status) {
Toast.makeText(GeoloqiExampleActivity.this, "Complete", Toast.LENGTH_LONG).show();
}
});
} else{
Toast.makeText(this, "service null", Toast.LENGTH_LONG).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
LQBinder binder = (LQBinder) service;
mService = binder.getService();
mBound = true;
sendRequest();//Sending API Request
} catch (ClassCastException e) {
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
GeoReceiver.java
public class GeoReceiver extends LQBroadcastReceiver {
#Override
public void onLocationChanged(Context arg0, Location arg1) {
Toast.makeText(arg0, "Loc Changed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPushMessageReceived(Context context, Bundle data) {
Toast.makeText(context, "Push Msg Received ", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationUploaded(Context arg0, int arg1) {
Toast.makeText(arg0, "Location Uploaded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onTrackerProfileChanged(Context arg0, LQTrackerProfile oldp,
LQTrackerProfile newp) {
Toast.makeText(arg0, "onTrackerProfileChanged ",Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pop.geoloqi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<permission
android:name="com.pop.geoloqi.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.pop.geoloqi.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".GeoloqiExampleActivity"
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>
<service
android:name="com.geoloqi.android.sdk.service.LQService"
android:exported="false" />
<receiver
android:name=".GeoReceiver"
android:enabled="false"
android:exported="false" >
<intent-filter>
<action android:name="com.geoloqi.android.sdk.action.LOCATION_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="com.geoloqi.android.sdk.receiver.LQDeviceMessagingReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.pop.geoloqi" />
</intent-filter>
</receiver>
</application>
</manifest>
There was a bug in earlier versions of the Geoloqi Android SDK. If you update to the latest version this problem should be resolved.
I have written the android application and I want the application to send the call information whenever there is an incoming call and it ends. This way I would be sending all calls to the server irrespective of size of the call log.
Here is the code
public class PhoneInfo extends BroadcastReceiver {
private int incoming_call = 0;
private Cursor c;
Context context;
public void onReceive(Context con, Intent intent) {
c = con.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC");
context = con;
IncomingCallListener phoneListener = new IncomingCallListener();
TelephonyManager telephony = (TelephonyManager) con
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
public class IncomingCallListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (incoming_call == 1) {
CollectSendCallInfo();
incoming_call = 0;
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_RINGING:
incoming_call = 1;
break;
}
}
private void CollectSendCallInfo() {
int numberColumn = c
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int durationColumn = c
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
ArrayList<String> callList = new ArrayList<String>();
try {
boolean moveToFirst = c.moveToFirst();
}
catch (Exception e) {
; // could not move to the first row.
return;
}
int row_count = c.getCount();
int loop_index = 0;
int is_latest_call_read = 0;
String callerPhonenumber = c.getString(numberColumn);
int callDate = c.getInt(dateColumn);
int callType = c.getInt(typeColumn);
int duration = c.getInt(durationColumn);
while ((loop_index < row_count) && (is_latest_call_read != 1)) {
switch (callType) {
case android.provider.CallLog.Calls.INCOMING_TYPE:
is_latest_call_read = 1;
break;
case android.provider.CallLog.Calls.MISSED_TYPE:
break;
case android.provider.CallLog.Calls.OUTGOING_TYPE:
break;
}
loop_index++;
c.moveToNext();
}
SendCallInfo(callerPhonenumber, Integer.toString(duration),
Integer.toString(callDate));
}
private void SendCallInfo(String callerPhonenumber, String callDuration,
String callDate) {
JSONObject j = new JSONObject();
try {
j.put("Caller", callerPhonenumber);
j.put("Duration", callDuration);
j.put("CallDate", callDate);
} catch (JSONException e) {
Toast.makeText(context, "Json object failure!", Toast.LENGTH_LONG)
.show();
}
String url = "http://xxxxxx.xxx.xx/xxxx/xxx.php";
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("phonecall", j.toString());
HttpResponse re;
try {
re = doPost(url, kvPairs);
String temp;
try {
temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS") == 0) {
;
}
else
;
} catch (ParseException e1) {
Toast.makeText(context, "Parse Exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Io exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
} catch (ClientProtocolException e1) {
Toast.makeText(context, "Client Protocol Exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Client Protocol Io exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
}
}
and here is the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Friend" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"></uses-permission>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Friend" 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=".LoginInfo" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.DEFAULT" />
</intent-filter>
</activity>
<service android:exported="true" android:enabled="true"
android:name=".GeoUpdateService">
</service>
<receiver android:name=".SmsInfo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver android:name=".PhoneInfo">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
The application just crashes when there is an incoming call. I have been able to log the information about incoming SMS, but this call info logging is failing.
In my opinion you use BroadcastReciver in wrong way. You perform sync-query which can last more time than you have for handling broadcast. Next issue - you register listener object which will be probably collected by GC just after the end of onReceive method. Your BroadR should start service for handling those events.