Android AlarmManager - Get AlarmID when alarm is triggered - android

I have an app that creates multiple alarms. Everything works fine, however, for some other functions (like updating a log) I need to retrieve the alarmID when the alarm is fired.
Here is the code the alarms are set with:
public void setAlarm(){
Intent intentAlarm = new Intent(c,AlarmReceiver.class);
intentAlarm.putExtra("userid", userid);
// create the object
AlarmManager alarmManager = (AlarmManager)
c.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent;
alarmIntent = PendingIntent.getActivity(c, alarmID, intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeToMiliseconds(hour,minute),
AlarmManager.INTERVAL_DAY,alarmIntent);
Toast.makeText(c,"Alarm set for " + toTime(hour,minute),Toast.LENGTH_SHORT).show();
Log.d("setAlarm()",alarm.toString());
}
The alarm receiver is an activity (which works fine). I just need to retrieve the alarms ID that's currently being fired.
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
private String scanContent;
private static final int ZBAR_SCANNER_REQUEST = 0;
String userid;
Button backBtn;
private PowerManager.WakeLock wakelock;
private ListView medBoxList;
ArrayList<HashMap<String, String>> medList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
ActionBar actionBar = getActionBar();
actionBar.hide();
/**
* Wakeup device if it's sleeping
*/
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wakelock.acquire();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Intent alarmActivityIntent = getIntent();
userid = alarmActivityIntent.getStringExtra("userid");
playSound(this, getAlarmUri());
Toast.makeText(this, "Take Medication", Toast.LENGTH_LONG).show();
Button stopAlarm = (Button) findViewById(R.id.scanQR);
Button skipBtn = (Button) findViewById(R.id.skipBtn);
backBtn = (Button)findViewById(R.id.backBtn);
//Click button to scan and update userlog
//Click button to scan and update userlog
stopAlarm.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mMediaPlayer.stop();
launchQRScanner();
}
});
//Click button to skip
skipBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mMediaPlayer.stop();
}
});
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
public void launchQRScanner() {
mMediaPlayer.stop();
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mMediaPlayer.stop();
scanContent = data.getStringExtra(ZBarConstants.SCAN_RESULT);
finish();
if(scanContent != null){
updateUserLog(scanContent);
Intent nextScreen = new Intent(getApplicationContext(),UserlogListActivity.class);
startActivity(nextScreen);
}
}
//Disable alarm with button instead of scan
public void alarmStopper(View v){
mMediaPlayer.stop();
Intent nextScreen = new Intent(getApplicationContext(),UserlogListActivity.class);
startActivity(nextScreen);
}
//TAKE MED ACTIVITY (MOVE TO )
public void updateUserLog(String scanContent){
//Toast.makeText(this, "Adding Userlog = " + scanContent, Toast.LENGTH_SHORT).show();
if(scanContent != null){
String userid,medname,tabstaken,dob;
//Break the scan content into strings for each variable
StringTokenizer st = new StringTokenizer(scanContent, ",");
dob = st.nextToken();
medname = st.nextToken();
tabstaken = st.nextToken();
if(dob != "" && medname != "" && tabstaken != ""){
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> userLog = new HashMap<String, String>();
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
//Store the userlog by passing to UserLogEntry
userid = user.get("uid");
if(userid != ""){
userLog = db.getNewestUserLogEntryForMed(medname);
String tabstr = userLog.get("tabsleft");
Log.d ("getNewestUserLogEntryForMed()", "medname " + userLog.get("medname") + " timetaken "
+ userLog.get("medtaken") + " Tabs - " + tabstr);
int tabs = Integer.parseInt(tabstr);
tabs = tabs - 1;
String tabsupdated = Integer.toString(tabs);
Log.d ("Tabs Updated - ", "medname " + userLog.get("medname") + " timetaken "
+ userLog.get("medtaken") + " Tabs - " + tabsupdated);
UserLogEntry userlog = new UserLogEntry(getApplicationContext(),userid,medname,tabsupdated);
userlog.addUserLog();
finish();
}
}
}
}
Any tips?
Much appreciated

So the answer was staring me in the face. I can use bundle to pass whatever I need into the alarm intent. I already was passing the userid (incorrectly). I just have to remember whenever there is an intent, that I can use bundle to pass simple variables along with it.
Intent intentAlarm = new Intent(c,AlarmReceiver.class);
Bundle extras = new Bundle();
extras.putString("userid", userid);
extras.putInt("alarmID", alarmID);
extras.putString("userlogID", userlogID);
extras.putString("medname", medname);
intentAlarm.putExtras(extras);
I figured I'd answer my own question in case someone else needs to do something similar, but if this is not helpful a moderator can delete it.

Related

Exception :- android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Creating an alarm notification and just cant figure out why i keep running into the error of
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
it is failing on(in the schedule course alarm() part.
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, nextAlarmId, intentAlarm, PendingIntent.FLAG_ONE_SHOT));
Part one
private boolean createTestAlarm() {
long now = DateUtil.todayLong();
if (now <= DateUtil.getDateTimestamp(course.start)) {
AlarmHandler.scheduleCourseAlarm(getApplicationContext(), courseId, DateUtil.getDateTimestamp(course.start),
"Course starts today!", course.name + " begins on " + course.start);
}
part two
public class AlarmHandler extends BroadcastReceiver {
public static final String courseAlarmFile = "courseAlarms";
public static final String assessmentAlarmFile = "assessmentAlarms";
public static final String alarmFile = "alarmFile";
public static final String nextAlarmField = "nextAlarmId";
#Override
public void onReceive(Context context, Intent intent) {
String destination = intent.getStringExtra("destination");
if (destination == null || destination.isEmpty()) {
destination = "";
}
int id = intent.getIntExtra("id", 0);
String alarmTitle = intent.getStringExtra("title");
String alarmText = intent.getStringExtra("text");
int nextAlarmId = intent.getIntExtra("nextAlarmId", getAndIncrementNextAlarmId(context));
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_calendar_clock)
.setContentTitle(alarmTitle)
.setContentText(alarmText);
Intent resultIntent;
Uri uri;
SharedPreferences sharedPreferences;
switch (destination) {
case "course":
Course course = DatabaseControl.getCourse(context, id);
if (course != null && course.notifications == 1) {
resultIntent = new Intent(context, CourseViewerActivity.class);
uri = Uri.parse(DatabaseData.COURSES_URI + "/" + id);
resultIntent.putExtra(DatabaseData.COURSE_CONTENT_TYPE, uri);
}
else {
return;
}
break;
case "assessment":
Assessment assessment = DatabaseControl.getAssessment(context, id);
if (assessment != null && assessment.notifications == 1) {
resultIntent = new Intent(context, AssessmentViewerActivity.class);
uri = Uri.parse(DatabaseData.ASSESSMENTS_URI + "/" + id);
resultIntent.putExtra(DatabaseData.ASSESSMENT_CONTENT_TYPE, uri);
}
else {
return;
}
break;
default:
resultIntent = new Intent(context, MainActivity.class);
break;
}
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent).setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(nextAlarmId, builder.build());
}
public static boolean scheduleCourseAlarm(Context context, long id, long time, String title, String text) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int nextAlarmId = getNextAlarmId(context);
Intent intentAlarm = new Intent(context, AlarmHandler.class);
intentAlarm.putExtra("id", id);
intentAlarm.putExtra("title", title);
intentAlarm.putExtra("text", text);
intentAlarm.putExtra("destination", "course");
intentAlarm.putExtra("nextAlarmId", nextAlarmId);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, nextAlarmId, intentAlarm, PendingIntent.FLAG_ONE_SHOT));
SharedPreferences sp = context.getSharedPreferences(courseAlarmFile, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(Long.toString(id), nextAlarmId);
editor.commit();
incrementNextAlarmId(context);
return true;
}
private static int getNextAlarmId(Context context) {
SharedPreferences alarmPrefs;
alarmPrefs = context.getSharedPreferences(alarmFile, Context.MODE_PRIVATE);
int nextAlarmId = alarmPrefs.getInt(nextAlarmField, 1);
return nextAlarmId;
}
private static void incrementNextAlarmId(Context context) {
SharedPreferences alarmPrefs;
alarmPrefs = context.getSharedPreferences(alarmFile, Context.MODE_PRIVATE);
int nextAlarmId = alarmPrefs.getInt(nextAlarmField, 1);
SharedPreferences.Editor alarmEditor = alarmPrefs.edit();
alarmEditor.putInt(nextAlarmField, nextAlarmId + 1);
alarmEditor.commit();
}
private static int getAndIncrementNextAlarmId(Context context) {
int nextAlarmId = getNextAlarmId(context);
incrementNextAlarmId(context);
return nextAlarmId;
}
}
part 3 -database code
public static Course getCourse(Context context, long courseId) {
Cursor cursor = context.getContentResolver().query(DatabaseData.COURSES_URI, Database.COURSES_COLUMNS,
Database.COURSES_TABLE_ID + " = " + courseId, null, null);
cursor.moveToFirst();
Long termId = cursor.getLong(cursor.getColumnIndex(Database.COURSE_TERM_ID));
String courseName = cursor.getString(cursor.getColumnIndex(Database.COURSE_NAME));
String courseDescription = cursor.getString(cursor.getColumnIndex(Database.COURSE_DESCRIPTION));
String courseStart = cursor.getString(cursor.getColumnIndex(Database.COURSE_START));
String courseEnd = cursor.getString(cursor.getColumnIndex(Database.COURSE_END));
String courseMentor = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR));
String courseMentorPhone = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR_PHONE));
String courseMentorEmail = cursor.getString(cursor.getColumnIndex(Database.COURSE_MENTOR_EMAIL));
String courseNote = cursor.getString(cursor.getColumnIndex(Database.COURSE_NOTE));
int courseNotifications = (cursor.getInt(cursor.getColumnIndex(Database.COURSE_NOTIFICATIONS)));
Course c = new Course();
c.courseId = courseId;
c.termId = termId;
c.name = courseName;
c.description = courseDescription;
c.start = courseStart;
c.end = courseEnd;
c.mentor = courseMentor;
c.mentorPhone = courseMentorPhone;
c.mentorEmail = courseMentorEmail;
c.note = courseNote;
c.notifications = courseNotifications;
return c;
}
Sure the error message says:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
So this means:
CursorIndexOutOfBoundsException think of a cursor as a collection, you are out of bounds
Index 0 requested You wanted to access at position 0 in the collection
with a size of 0 but the collections size is 0 (empty) therefore Out of Bounds.
If you are expecting your database schema to be correct you should not use getColumnIndex but use getColumnIndexOrThrow https://developer.android.com/reference/android/database/Cursor#getColumnIndexOrThrow(java.lang.String) that way you will fail fast and see which part of your data is incorrect.
But yeah basically your cursor is empty, check the query that you are doing. You can also breakpoint on a cursor, and to try alternative queries on teh content resolver.
You could also use a Tool like Stetho, to inspect your on device database to see if it has any data (and practice some queries)
http://facebook.github.io/stetho/
Or move away from cursors altogther and use opne of the newer recommended database access libraries like Room:
https://developer.android.com/topic/libraries/architecture/room

Notification created from Service disappears from status bar

I have a webservice and I am using ksoap2 to connect to it and upload some pictures.
The process is:
Open the gallery
Select a few pictures
Share to my app
Start a foreground service
send the basic information to this service, like an array with all the picture's path
handle the intent and take the bundles
and start the foreground notification with the proper flag and with startForeground(id,noty)
The problem:
Everything goes right. Uploading and showing the items uploaded ...until...suddenly the notification just disappear from the bar.
After a while it shows by itself again and continues the upload, I tried to set some stuff to get the last item uploaded and start from there, I don't know if I am doing right and I would like to have an advice about this.
This is the Activity from where I call the Service:
Intent mServiceIntent = new Intent(this, UploadService.class);
Bundle bund = new Bundle();
bund.putStringArray("pathList", pictureList);
bund.putString("tags", tag);
boolean hasGeotag = UserManagerClass.UserLogged.isActiveLocation();
bund.putBoolean("hasGeotag", hasGeotag);
if (hasGeotag) {
GeoTag gtag = UserManagerClass.UserLocation;
bund.putDouble("latitude", gtag.getLatitude());
bund.putDouble("longitude", gtag.getLongitude());
bund.putString("city", gtag.getCity());
bund.putString("country", gtag.getCountry());
bund.putString("address", gtag.getAddress());
}
bund.putInt("idOwner", IDOWNER);
bund.putInt("idUser", UserManagerClass.UserLogged.getID());
bund.putInt("albumindex", albumIndex);
bund.putInt("privacyindex", privacyIndex);
bund.putString("comment", comment);
mServiceIntent.putExtras(bund);
startService(mServiceIntent);
and this is the code of the Service:
public class UploadService extends Service {
private static final int myID = 1433;
private static final String PREF_NAME = "SERVICEUPLOAD";
private static final String UPLOADED_PATH = "UPLOADED_";
private static int position;
private int albumIndex;
private String comment;
private boolean hasGeotag;
private int idOwner;
private int idUser;
private GeoTag location;
private String[] pathList;
private int privacyIndex;
private SoapPost sp;
private String tags;
private NotificationManager nManager;
private PendingIntent pi;
#Override
public void onCreate() {
Log.e("step 1", "entered to create");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private void exit() {
Log.e("step 10", "ending...");
deletePosition();
Log.e("step 12", "ended");
this.stopForeground(true);
updateNotification(true);
}
void createNotification() {
Log.e("step 4", "entered to create notification");
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = getText(R.string.upload_waiting);
//
pi = PendingIntent.getActivity(this, 0, new Intent(), Notification.FLAG_FOREGROUND_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.add_comment_icon);
builder.setTicker(text);
builder.setContentIntent(pi);
builder.setContentText(text);
builder.setContentTitle(text);
startForeground(myID, builder.build());
}
private void updateNotification(boolean completed) {
Log.e("step 8", "updating notification");
String ticker = String.format(getResources().getString(R.string.upload_uploading_tick), position);
String message = String.format(getResources().getString(R.string.upload_uploading_message_progress), position, pathList.length);
String title = String.format(getResources().getString(R.string.upload_uploading_title), position);
String title_completed = getResources().getString(R.string.upload_uploading_title_completed);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.add_comment_icon);
builder.setContentText(message);
builder.setTicker(ticker);
if (!completed)
builder.setContentTitle(title);
else {
builder.setContentTitle(title_completed);
pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
}
builder.setContentIntent(pi);
if (completed)
nManager.notify(myID, builder.build());
else
startForeground(myID, builder.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("step 2", "entered to onstart");
handleIntent(intent);
return START_STICKY;
}
void handleIntent(Intent data) {
Log.e("step 3", "entered to handle");
// GETS THE POSITIONS IF THE SERVICE WAS STOPPED BEFORE
// RETURN 0 IF IT WASNT
getPosition();
//
if (data == null)
this.stopForeground(true);
Bundle dt = data.getExtras();
tags = dt.getString("tags");
pathList = dt.getStringArray("pathList");
hasGeotag = dt.getBoolean("hasGeotag");
if (hasGeotag) {
location = new GeoTag();
location.setLatitude(dt.getDouble("latitude"));
location.setLongitude(dt.getDouble("longitude"));
location.setAddress(dt.getString("address"));
location.setCity(dt.getString("city"));
location.setCountry(dt.getString("country"));
}
idOwner = dt.getInt("idOwner");
idUser = dt.getInt("idUser");
albumIndex = dt.getInt("albumindex");
privacyIndex = dt.getInt("privacyindex");
comment = dt.getString("comment");
// isCover = dt.getBoolean("isCover");
sp = new SoapPost();
// CREATES THE NOTFICATION
createNotification();
// FINALLY SEND THE DATA TO THE WEB SERVICE
sendData();
}
private void sendData() {
Log.e("step 4", "entered to send data");
for (String fl : pathList) {
Log.e("step 5", "sending... " + fl);
if (fl != null && !fl.equals(UPLOADED_PATH)) {
try {
String[] dataup = new String[10];
if (hasGeotag) {
dataup = new String[15];
dataup[10] = String.valueOf(location.getLatitude());
dataup[11] = String.valueOf(location.getLongitude());
dataup[12] = location.getAddress();
dataup[13] = location.getCity();
dataup[14] = location.getCountry();
}
if (comment.length() > 0)
dataup[0] = URLEncoder.encode(comment, "UTF-8");
else
dataup[0] = "";
dataup[1] = String.valueOf(idOwner);
dataup[2] = String.valueOf(idUser);
dataup[3] = "2";
dataup[4] = "";
dataup[5] = String.valueOf(albumIndex);
dataup[6] = String.valueOf(privacyIndex);
dataup[7] = "";
dataup[8] = "";
dataup[9] = "";
File file = new File(fl);
// CONTINUE ONLY IF THE FILE EXISTS
if (file.exists()) {
Log.e("step 6", "file exists true");
// SETTING WIDTH AND HEIGHT
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fl, options);
int wth = options.outWidth;
int hth = options.outHeight;
long lenght = file.length();
// END W AND H
String b64 = null;
b64 = Base64.encodeToString(PictureManagerClass.getBytesFromFile(file), Base64.DEFAULT);
file = null;
// SETTING
// 4 BASE64
// 7 W
// 8 H
// 9 L
dataup[4] = b64;
dataup[7] = String.valueOf(wth);
dataup[8] = String.valueOf(hth);
dataup[9] = String.valueOf(lenght);
Log.e("step 7", "uploading... " + fl);
// SET THE CURRENT ITEM AS UPLOADED
pathList[position] = null;
// SAVE THE ACTUAL POSITION
savePosition();
sp.uploadPicture(dataup, tags, SoapPost.UPLOAD_PICTURE);
position++;
updateNotification(false);
}// END FILE EXISTS
}
catch (Exception ex) {
// SAVE THE ACTUAL POSITION
savePosition();
//
StackTraceElement[] stack = ex.getStackTrace();
String Trace = " ";
for (StackTraceElement line : stack) {
Trace += line.toString();
}
Log.e("SERVICE: ", Trace);
}
}// END FL NULL
}// END FOR
exit();
}
#Override
public void onDestroy() {
// SAVE THE ACTUAL POSITION
savePosition();
super.onDestroy();
}
#Override
public void onLowMemory() {
// SAVE THE ACTUAL POSITION
savePosition();
super.onLowMemory();
}
void savePosition() {
Log.e("step 9", "saving position");
// SET THE VALUES FROM PATHS TO SET TO SAVE IT INTO PREFERENCES
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("position", position);
Set<String> set = new HashSet<String>();
if (pathList != null) {
for (int i = 0; i < position; i++)
pathList[i] = null;
for (int i = position; i < pathList.length; i++)
if (pathList[i] != null)
set.add(pathList[i]);
}
if (pathList != null)
editor.putStringSet("pathList", set);
editor.commit();
}
void getPosition() {
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
position = prefs.getInt("position", 0);
Log.e("step 3.1", position + "");
Set<String> set = new HashSet<String>();
set = prefs.getStringSet("pathList", set);
int pos = 0;
for (String path : set) {
pathList = new String[set.size()];
pathList[pos] = path;
pos++;
}
}
void deletePosition() {
Log.e("step 11", "clear...");
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
/* (non-Javadoc)
* #see android.app.Service#onBind(android.content.Intent)
*/
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
FIXED
i fixed it...this is the new method sendData():
private void sendData() {
new Thread(new Runnable() {
#Override
public void run() {
for (String fl : pathList) {
if (fl != null && !fl.equals(UPLOADED_PATH)) {
try {
String[] dataup = new String[10];
if (hasGeotag) {
dataup = new String[15];
dataup[10] = String.valueOf(location.getLatitude());
dataup[11] = String.valueOf(location.getLongitude());
dataup[12] = location.getAddress();
dataup[13] = location.getCity();
dataup[14] = location.getCountry();
}
if (comment.length() > 0)
dataup[0] = URLEncoder.encode(comment, "UTF-8");
else
dataup[0] = "";
dataup[1] = String.valueOf(idOwner);
dataup[2] = String.valueOf(idUser);
dataup[3] = "2";
dataup[4] = "";
dataup[5] = String.valueOf(albumIndex);
dataup[6] = String.valueOf(privacyIndex);
dataup[7] = "";
dataup[8] = "";
dataup[9] = "";
File file = new File(fl);
// CONTINUE ONLY IF THE FILE EXISTS
if (file.exists()) {
// SETTING WIDTH AND HEIGHT
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fl, options);
int wth = options.outWidth;
int hth = options.outHeight;
long lenght = file.length();
// END W AND H
byte[] pic = PictureManagerClass.getBytesFromFile(file);
Log.e("picLength", pic.length + "");
file = null;
// SETTING
// 4 BASE64
// 7 W
// 8 H
// 9 L
dataup[4] = "";
dataup[7] = String.valueOf(wth);
dataup[8] = String.valueOf(hth);
dataup[9] = String.valueOf(lenght);
Log.e("step 7", "uploading... " + fl);
// SET THE CURRENT ITEM AS UPLOADED
pathList[position] = null;
// SAVE THE ACTUAL POSITION
savePosition();
String mes = sp.uploadPicture(dataup, tags, SoapPost.UPLOAD_PICTURE, pic);
Log.e("picID", mes);
pic = null;
dataup = null;
position++;
updateNotification(false);
Thread.sleep(1 * 1000);
}// END FILE EXISTS
}
catch (Exception ex) {
// SAVE THE ACTUAL POSITION
savePosition();
//
StackTraceElement[] stack = ex.getStackTrace();
String Trace = " ";
for (StackTraceElement line : stack) {
Trace += line.toString();
}
Log.e("SERVICE: ", Trace);
}
}// END FL NULL
}// END FOR
exit();
}
}).start();;
}
and now the notification doesnt hide until all files were uploaded ... thanks.

getIntent() not capturing data properly

I am passing row id with the help of intent. The calling method being a custom adapter -
holder.text.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "TEXT CLICKED" + pos , Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,ReminderModificationActivity.class);
long longPos = (long)pos;
intent.putExtra(TasksDBAdapter.KEY_ROWID, pos);
Log.i(TAG, "row clickd --> " + longPos);
((Activity) context).startActivityForResult(intent, ACTIVITY_EDIT);
}
});
OnCreate() method of ReminderModificationActivity try to retrieve the data.Code -
protected void onCreate(Bundle savedInstanceState){
dbHelper = new TasksDBAdapter(this);
//set current theme
settingsDBAdapter = new SettingsDBAdapter(this);
settingsDBAdapter.open();
setSettingsTheme();
setContentView(R.layout.reminder_modify);
mCalendar = Calendar.getInstance();
Log.i(getLocalClassName(), "VALUE of Button--->" + findViewById(R.id.SetDateButtonId));
mDateButton = (Button) findViewById(R.id.SetDateButtonId);
mTimeButton = (Button) findViewById(R.id.SetTimeButtonId);
mConfirmButton = (Button) findViewById(R.id.SaveButtonId);
mTitleText = (EditText) findViewById(R.id.TitleEditTextId);
mBodyText = (EditText) findViewById(R.id.DescriptionEditTextId);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(TasksDBAdapter.KEY_ROWID) : null ;
registerButtonListenersAndSetDefaultText();
Log.i(TAG, "getIntent-->" + getIntent() + mRowId);
//code to check what row id have been passed
if(getIntent() != null) {
---->>>MAIN CODE
Log.i(TAG, "mRowId in getintent-->" + mRowId + "row id passed-->" + getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1));
mRowId = getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1);
// Do stuff with the row id here
if(mRowId != -1){
//code if RowId valid
}
}
super.onCreate(savedInstanceState);
Log.i(TAG, "mROwId in onCreate ReminderNotification again-->" + mRowId);
}
line marked as MAIN CODE captures the intent data but Log.i gives value of
getIntent().getLongExtra(TasksDBAdapter.KEY_ROWID, -1))
as -1.Can sumone please help me out on this.Thanks in advance,Ray
Seeing as you cast pos to longPos, you should be using longPos in your intent extra, but you use pos.
if you were to change your code to:
Intent intent = new Intent(context,ReminderModificationActivity.class);
long longPos = (long)pos;
intent.putExtra(TasksDBAdapter.KEY_ROWID, longPos); //<< changed to longPos
It should work

Android: detect when app is installed

I am trying to download an Android app from a server using the DownloadManager class, install it and then detect when the installation is completed. I am using two receivers: one to detect the download process and the other to detect the install process. The first receiver works properly, but the second doesn't. What I am doing wrong?
DownloadManager dm = (DownloadManager) DownloadApplicationActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(MY_LINK));
req.setTitle(MY_TITLE)
.setDescription("Downloading ....")
// download the package to the /sdcard/downlaod path.
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
MY_PATH);
long enqueue = dm.enqueue(req);
BroadcastReceiver receiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(enqueue);
Cursor c =dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
// show a notification bar.
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,"",System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_NO_CLEAR;
Intent i = new Intent(Intent.ACTION_VIEW);
// when the notification is clicked, install the app.
i.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory() + APP_PATH)),"application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(
activity, 0, i, 0);
notification.setLatestEventInfo(activity, MY_TEXT, MY_TEXT,pendingIntent);
notification.number += 1;
notificationManager.notify( 0, notification);
//i want to detect the app's installation, I register a ne receiver
registerReceiver(installReceiver,new IntentFilter(Intent.ACTION_PACKAGE_ADDED));
}
}
};
BroadcastReceiver installReceiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
Uri data = intent.getData();
String packageName = data.getEncodedSchemeSpecificPart();
Log.i("The installed package is: ", "" + packageName);
}
}
};
I solved my problem, I added
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
intentFilter.addDataScheme("package");
before the line :
registerReceiver(installReceiver, intentFilter);
You can try the code below. This way you can get all activities that can be called by an intent and if you know the activity name and it is present in list retrieved by queryIntentActivities()..you know it is installed.
public void callQrScan()
{
Intent intent1 = new Intent("com.google.zxing.client.android.SCAN");
if(isCallable(intent1)== true){
Context context = getApplicationContext();
CharSequence text = "Scan Niet Gelukt";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else{
Context context = getApplicationContext();
CharSequence text = "Scan Niet Gelukt";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Button tempbutton = (Button)findViewById(R.id.Button03);
tempbutton.setOnClickListener(new OnClickListener()
{
public void onClick(final View v)
{
callQrScan();
}
});
}
private boolean isCallable(Intent intent1) {
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent1,
PackageManager.MATCH_DEFAULT_ONLY);
if(list.size() > 0)
return true ;
else
return false;
}
Hope it helps :)

Use application to rate it on market [duplicate]

This question already has answers here:
"Rate This App"-link in Google Play store app on the phone
(21 answers)
Closed 2 years ago.
I am currently developing an application in Android Where I want to give some functionality to user to rate the current application.
Their will be a button on it's click it will ask ask whether user want to rate the application or not? If yes will will go to market application on device to rate application
(Market should show this application.) or it will open browser which will load market & showing this application.
Any one used this kind of functionality before. Please provide some help.
Thank You.
I always use a method like this one:
private void launchMarket() {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.couldnt_launch_market, Toast.LENGTH_LONG).show();
}
}
public class AppRater {
private final static String APP_TITLE = "App Name";// App Name
private final static String APP_PNAME = "com.example.name";// Package Name
private final static int DAYS_UNTIL_PROMPT = 3;//Min number of days
private final static int LAUNCHES_UNTIL_PROMPT = 3;//Min number of launches
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}}
Now Integrate class to your activity like this ->
AppRater.app_launched(this);
Here is simple solution for :
final String appPackageName = "com.name.app";
private void launchMyMarket() {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(myAppLinkToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, " unable to find source market app! try again", Toast.LENGTH_LONG).show();
}
}
The answers here won't take you directly to playstore if you have multiple market apps on your phone. Instead it will show a picker dialog.
To open playstore directly, use this:
private fun rateUs() {
val uri = Uri.parse("https://play.google.com/store/apps/details?id=" + activity?.packageName.toString() + "")
val intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
}

Categories

Resources