Android AlarmManager Won't Start Service - java

I have two implementations of AlarmManager which are supposed to start two services - LMW and BWM - for some reason BWM starts each time and LMW does not. I've looked the source code over many times and I'm really not sure why this could be happening.
P.S.
adb shell dumpsys alarm shows a reference to BWM but no reference to LWM
Any input is greatly appreciated!
ALARMMANAGER SOURCE:
public class Rules extends Activity {
private String password;
private PendingIntent mPendingIntent;
String TIMELIMIT = "10";
TextView textSsid, textSpeed, textRssi, Time;
private static final int NOTIFY_ME_ID = 1337;
private int count = 0;
private NotificationManager notifyMgr = null;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rules);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
Time = (TextView) findViewById(R.id.Time);
Time.setText(time);
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Time = (TextView) findViewById(R.id.Time);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED
|| mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView) findViewById(R.id.RX);
TextView TX = (TextView) findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer) findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public Date getTimeFromTimeString(String time) {
String[] splitStrings = time.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
return timeDate;
}
// Long.parseLong(time)
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed())
+ " " + WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
;
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
// Start 2nd service using AlarmManager
// Calendar cal = Calendar.getInstance();
// cal.add(Calendar.SECOND, 10);
// Intent intent2 = new Intent(Rules.this, KillTimer.class);
// PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0,
// intent2,
// 0);
// AlarmManager alarm2 = (AlarmManager)
// getSystemService(Context.ALARM_SERVICE);
// alarm2.setRepeating(AlarmManager.RTC_WAKEUP,
// cal.getTimeInMillis(),
// time != null ? 1000 : 0, pintent2);
// Date futureDate = new Date(new Date().getTime() + 86400000);
// futureDate.setHours(8);
// futureDate.setMinutes(0);
// futureDate.setSeconds(0);
// Start 3rd service using AlarmManager
Intent intent3 = new Intent(Rules.this, BWM.class);
PendingIntent pintent3 = PendingIntent.getActivity(Rules.this, 0,
intent3, 0);
AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent3);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), LMW.class));
startService(new Intent(getBaseContext(), BWM.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), LMW.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
}
};
}
LMW SOURCE:
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!",
Toast.LENGTH_SHORT).show();
Parse.initialize(this, "7gjqmUcoqu1IZPJSSxXLdE4L8efAugCXA7snLSH6",
"5NckF83MUBumQ8L8zL7Akc4p07beMRnmvgCfhZdH");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground();
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(
android.provider.Browser.BOOKMARKS_URI, projection, null, null,
null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor
.getColumnIndex(Browser.BookmarkColumns.URL));
// Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1)
|| url.toLowerCase().contains(Dirty2)
|| url.toLowerCase().contains(Dirty3)
|| url.toLowerCase().contains(Dirty4)
|| url.toLowerCase().contains(Dirty5)
|| url.toLowerCase().contains(Dirty6)
|| url.toLowerCase().contains(Dirty7)
|| url.toLowerCase().contains(Dirty8)
|| url.toLowerCase().contains(Dirty9)
|| url.toLowerCase().contains(Dirty10)) {
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
}
} while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}

Related

Android Alarm firing instantly when I set alarm on earlier hour or after midnight [duplicate]

This question already has an answer here:
android prevent immediate trigger of alarm service if alarm time has passed for the day
(1 answer)
Closed 4 years ago.
Im creating my first app in Android Studio. My Alarm Clock is working almost well, but when I will set Alarm to hour earlier than current or after midnight my alarm is firing instantly. For example, current time is 17:00, when I set alarm for 17:05 everything is fine, but when alarm is for 16:00 or 00:05 alarm is firing instantly. I will be thankful for all your advices. Here is my code:
Alarm.java
public class Alarm extends AppCompatActivity {
private TimePicker timePicker;
private Button vibrationButton;
private Button soundButton;
private Button noteButton;
private Button saveButton;
private Button cancelButton;
private CheckBox wifiCheckBox;
private CheckBox soundCheckBox;
private CheckBox bluetoothCheckBox;
private TextView textView;
private BluetoothAdapter mBluetoothAdapter;
private WifiManager wiFi;
private AudioManager audioManager;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private Intent intent;
private int hour;
private int minute;
private String minuteString;
private String hourString;
private void turnOnWifi() {
if (wifiCheckBox.isChecked())
wiFi.setWifiEnabled(true);
}
private void turnOnBluetooth() {
if (bluetoothCheckBox.isChecked())
mBluetoothAdapter.enable();
}
private void turnOnSound() {
if (soundCheckBox.isChecked())
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
private void notification() {
Intent intentNotification = new Intent(this.getApplicationContext(),Alarm.class);
PendingIntent pendingIntentNotification = PendingIntent.getActivity(this, 0, intentNotification, 0);
Notification notification = new Notification.Builder(this)
.setContentTitle("Alarm")
.setContentText("Next alarm: " + hourString + ":" + minuteString)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(false)
.setSmallIcon(R.mipmap.ic_launcher)
.build();
notificationManager.notify(0, notification);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
timePicker = findViewById(R.id.timePicker);
vibrationButton = findViewById(R.id.vibrationButton);
soundButton = findViewById(R.id.soundButton);
noteButton = findViewById(R.id.noteButton);
saveButton = findViewById(R.id.saveButton);
cancelButton = findViewById(R.id.cancelButton);
wifiCheckBox = findViewById(R.id.wifiCheckBox);
soundCheckBox = findViewById(R.id.soundCheckBox);
bluetoothCheckBox = findViewById(R.id.bluetoothCheckBox);
textView = findViewById(R.id.textView);
wiFi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, AlarmReceiver.class);
timePicker.setIs24HourView(true);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
if (calendar.before(Calendar.getInstance()))
calendar.add(Calendar.DATE, 1);
if (Build.VERSION.SDK_INT >= 23) {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
calendar.set(Calendar.MINUTE, timePicker.getMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
calendar.set(Calendar.SECOND, 0);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
hourString = String.valueOf(hour);
minuteString = String.valueOf(minute);
if (hour == 0)
hourString = "0" + hourString;
if (minute < 10)
minuteString = "0" + minuteString;
textView.setText("Next alarm: " + hourString + ":" + minuteString);
intent.putExtra("extra", "on");
setAlarm(calendar.getTimeInMillis());
// notification();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Alarm off!");
alarmManager.cancel(pendingIntent);
intent.putExtra("extra", "off");
sendBroadcast(intent);
// notificationManager.cancel(0);
}
});
}
private void setAlarm(long timeInMillis) {
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("test","test123");
String getState = intent.getExtras().getString("extra");
Log.e("Key is: ", getState);
Intent intentService = new Intent(context, RingtoneService.class);
intentService.putExtra("extra", getState);
context.startService(intentService);
}
}
RingtoneService.java
public class RingtoneService extends Service {
private MediaPlayer mediaPlayer;
boolean isRunning;
int startId;
#Override
public void onDestroy() {
Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
this.isRunning = false;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
String state = intent.getExtras().getString("extra");
assert state != null;
switch (state) {
case "on":
startId = 1;
break;
case "off":
startId = 0;
break;
default:
startId = 0;
break;
}
if (!this.isRunning && startId == 1){
mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
this.isRunning = true;
this.startId = 0;
}
else if (this.isRunning && startId == 0){
mediaPlayer.stop();
mediaPlayer.reset();
this.isRunning = false;
this.startId = 0;
}
else if (!this.isRunning && startId == 0){
this.isRunning = false;
this.startId = 0;
}
else if (this.isRunning && startId == 1){
this.isRunning = true;
this.startId = 1;
}
return START_NOT_STICKY;
}
}
Of course it does... It's meant to work so.
Android recognizes that the time is past, so it will fire the alarm, even if it's late.
You can make sure that the time set for the alarm is after the current time. Just calculate this difference:
int diff = Calendar.getInstance().getTimeInMilis() - targetCal.getTimeInMillis();
If diff is greater than 0, then add a day to your calendar (targetCal)
Now, your device's time will be earlier (instead of being later) than the next scheduled alarm time.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
if(calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingDinnerIntent);

how to set alarm scheduling with notification in android?

I have a problem with my code. i first create an alarm with a notification,Then I set the alarm for the following times - 6AM, 12PM and 6PM. However when I run the application, the alarm is always on,and does not go on at 6AM, 12PM and 6PM. The notifications are also not on time. Im using toggle button.
My code :
AlarmFragmen.java`
public class AlarmFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private PendingIntent pendingIntent;
private TextView textViewEnamPagi, textViewDuabelas, textViewenamSore, textResult;
private ToggleButton toggleButtonEnamPagi, toggleButtonDuaBelas, toggleButtonEnamSore;
public AlarmFragment() {
}
public static AlarmFragment newInstance(String param1, String param2) {
AlarmFragment fragment = new AlarmFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_alarm, container, false);
toggleButtonEnamPagi = (ToggleButton) v.findViewById(R.id.toggleButton);
textViewEnamPagi = (TextView) v.findViewById(R.id.textViewEnamPagi);
textViewDuabelas = (TextView) v.findViewById(R.id.textView);
textViewenamSore = (TextView) v.findViewById(R.id.textEnamSore);
toggleButtonDuaBelas = (ToggleButton) v.findViewById(R.id.toggleButton2);
toggleButtonEnamSore = (ToggleButton) v.findViewById(R.id.toggleEnamSore);
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
textViewDuabelas.setText("OFF Pukul 12.00 PM");
textViewenamSore.setText("OFF Pukul 18.00 PM");
startSix();
startDuaBelas();
startEnamSore();
toggleButtonEnamPagi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamPagi.isChecked()){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", true);
edt.commit();
}else {
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", false);
edt.commit();
}
}
});
toggleButtonDuaBelas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonDuaBelas.isChecked()){
textViewDuabelas.setText("ON Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", true);
edt.commit();
}else{
textViewDuabelas.setText("OFF Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", false);
edt.commit();
}
}
});
toggleButtonEnamSore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamSore.isChecked()){
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", true);
edt.commit();
}else{
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", false);
edt.commit();
}
}
});
return v;
}
public void startSix(){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenam = preferences.getBoolean("tgEnam", true);
if(tgenam == true){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
toggleButtonEnamPagi.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startDuaBelas() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgduabelas = preferences.getBoolean("tgDuabelas", true);
if (tgduabelas == true) {
textViewDuabelas.setText("ON Pukul 12.00 PM");
toggleButtonDuaBelas.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 1, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startEnamSore() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenamsore = preferences.getBoolean("tgEnamsore", true);
if (tgenamsore == true) {
textViewenamSore.setText("ON Pukul 18.00 PM");
toggleButtonEnamSore.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 2, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
And MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, AlarmFragment.class);
service1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(service1);
Intent myIntent = new Intent(context, MyAlarmService.class);
context.startService(myIntent);
}
AlarmService.java
public class MyAlarmService extends Service{
NotificationManager manager;
Notification myNotication;
private NotificationManager mManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder builder = new Notification.Builder(MyAlarmService.this);
builder.getNotification().flags = Notification.FLAG_AUTO_CANCEL;
builder.setAutoCancel(true);
builder.setTicker("this is ticker text");
builder.setContentTitle("Alarm ON");
builder.setContentText("Wake UP");
builder.setSmallIcon(R.drawable.image);
builder.setContentIntent(pendingIntent);
//builder.setOngoing(true);
builder.setSubText("Time to code"); //API level 16
builder.setNumber(1);
builder.build();
builder.setVibrate(new long[]{1000,1000,1000,1000,1000});
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.song);
builder.setSound(uri);
myNotication = builder.getNotification();
manager.notify(0, myNotication);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Please help me to solve my problem, thx

Sending the notifications from service

The implementation of the notification sending does actually work if I send it from Activity, but nothing happens if I send from Service. Can anyone suggest possible solutions? Thanks
Here is my Service implementation..........
public class MyService extends Service {
private NotificationManager notificationManager;
private DBHelper dbHelper;
private SQLiteDatabase db;
private Context mContext = this;
private int notificationID = 100;
#Override
public void onCreate() {
Log.i("myLOgs", "Service: onCreate()");
super.onCreate();
dbHelper = new DBHelper(this);
db = dbHelper.getWritableDatabase();
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("myLOgs", "Service: onStartCommand()");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String currentDateString = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH-mm");
Date time = new Date();
String currentTimeString = timeFormat.format(time);
String[] columns = {DBHelper.DATE, DBHelper.TIME, DBHelper.EVENT};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
do {
String dateString = cursor.getString(cursor.getColumnIndex(DBHelper.DATE));
String timeString = cursor.getString(cursor.getColumnIndex(DBHelper.TIME));
String eventString = cursor.getString(cursor.getColumnIndex(DBHelper.EVENT));
boolean dateCompare = currentDateString.equals(dateString);
boolean timeCompare = currentTimeString.equals(timeString);
if((dateCompare) && (timeCompare)) {
Notify(eventString, "message");
}
if(cursor.moveToLast()) {
cursor.moveToFirst();
}
}while(true);
//return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void Notify(String notificationTitle, String bodytext){
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationID, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, bodytext, pendingIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationID++, notification);
}
}

Change Class After Notification Is Clicked Android

I am trying to change my class to to go to Login.java I have tried numerous solutions but can't seem to get it. I have a PromximityAlert set-up to check location and after that location is confirmed it will display the notification and when that notification is clicked, it will initiate the Login class.
Here is my code:
public class ProxAlertActivity extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in Milliseconds
private static final long POINT_RADIUS = 1000; // in Meters
private static final long PROX_ALERT_EXPIRATION = -1;
private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";
private static final String PROX_ALERT_INTENT = "com.example.mysqltest.ProximityAlert";
private static final NumberFormat nf = new DecimalFormat("##.########");
private LocationManager locationManager;
private EditText latitudeEditText;
private EditText longitudeEditText;
private Button findCoordinatesButton;
private Button savePointButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
latitudeEditText = (EditText) findViewById(R.id.point_latitude);
longitudeEditText = (EditText) findViewById(R.id.point_longitude);
findCoordinatesButton = (Button) findViewById(R.id.find_coordinates_button);
savePointButton = (Button) findViewById(R.id.save_point_button);
findCoordinatesButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
populateCoordinatesFromLastKnownLocation();
}
});
savePointButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveProximityAlertPoint();
}
});
}
private void saveProximityAlertPoint() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location==null) {
Toast.makeText(this, "No last known location. Aborting...", Toast.LENGTH_LONG).show();
return;
}
saveCoordinatesInPreferences((float)location.getLatitude(), (float)location.getLongitude());
addProximityAlert(location.getLatitude(), location.getLongitude());
}
private void addProximityAlert(double latitude, double longitude) {
Intent intent = new Intent(PROX_ALERT_INTENT);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(
41.69519672, // the latitude of the central point of the alert region
-87.80026184, // the longitude of the central point of the alert region
POINT_RADIUS, // the radius of the central point of the alert region, in meters
PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(new ProximityIntentReceiver(), filter);
}
private void populateCoordinatesFromLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null) {
latitudeEditText.setText(nf.format(location.getLatitude()));
longitudeEditText.setText(nf.format(location.getLongitude()));
}
}
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
prefsEditor.commit();
}
private Location retrievelocationFromPreferences() {
SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
Location location = new Location("POINT_LOCATION");
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY, 0));
return location;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
Location pointLocation = retrievelocationFromPreferences();
float distance = location.distanceTo(pointLocation);
Toast.makeText(ProxAlertActivity.this,
"Distance from Point:"+distance, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
}
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}
else {
Log.d(getClass().getSimpleName(), "exiting");
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_menu_notifications;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
Add this , I think its missing
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setContentIntent(pendingIntent );

Issue(s) Null Checking via LogCat - Data Does Not Appear In Log

I'm attempting to find the string or long values in my source code which return data (so I can post them to my server) however when I attempt to null check them using the following:
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
The data never appears in the logs. Any suggestions are greatly appreciated!
SERVICE CLASS SOURCE:
public class Service_class extends Service {
public static String TAG="TEST TAG";
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private TextView findViewById(int speed) {
// TODO Auto-generated method stub
return null;
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private Chronometer findViewById(int chronometer) {
// TODO Auto-generated method stub
return null;
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}}};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
// Log.d(TAG, "starting service");
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
MAIN.Java
public class Main extends Activity {
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
12 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
ParseAnalytics.trackAppOpened(getIntent());
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
};
};}
you may add one string(any dummy) value so that they will appear, i think
Log.d(TAG,"Null: "+String.valueOf(WifiInfo.LINK_SPEED_UNITS));

Categories

Resources