Verify if an intent take a valid activity - java

public void action(View view){
Intent intent = new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);
if(intent!=null) //here is my problem, it return true always
{startActivity(intent);}
else{k++;
Context context = getApplicationContext();
CharSequence mesajText = "Failed To Open! " + k;
int duration = 3;
Toast screen_message = Toast.makeText(context,mesajText,duration);
screen_message.show();
}
}
How can I verify if my 'intent' have a valid activity(works when it's open) or an invalid one(app crash when it's open)?

if(intent!=null) will always evaluate to true because your are initializing intent just before the if condition. If you want to check if Intent can be handled then use resolveActivity as follows:
Intent intent = new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
} else{
k++;
CharSequence mesajText = "Failed To Open! " + k;
int duration = 3;
Toast screen_message = Toast.makeText(this,mesajText,duration);
screen_message.show();
}

Related

How to access to the specific Folder in Android Studio?

I need to access the specific folder depending on the name of the created project. In Main_Activity the name of this project is filled and new folder is created. Thus, Camera_Activity saves the photos taken in that folder. Next I access Gallery_Activity, but it never goes to the folder of the created project. How can I access to that folder?
An example: Name of the created folder: Proj_1, but user select the photos from another one that opens by default, the uri that comes out is:
content://com.android.externalstorage.documents/document/primary%3APictures%2FCaptures_Camera2%2FProj_aa%2Fpic_040621_110254.jpeg
Part of AndroidManifest.xml
...
<uses-feature android:name="android.hardware.camera2.full" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
...
MainActivity.java
...
createNewProject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Coge el nombre de EditText, crea nueva carpeta y empieza la captura de las imagenes
if(newName.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "Please, fill in the field.", Toast.LENGTH_LONG).show();
} else {
name = newName.getText().toString();
GlobalVariables.ProjectName = name;
Intent intent = new Intent(MainActivity.this, Camera_Activity.class);
startActivity(intent);
}
}
});
...
Camera_Activity.java takes the necessary photos, saves them and has a button to enter the gallery:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTextureView = findViewById(R.id.camera_preview);
btn_take_pic = findViewById(R.id.button_take_photo);
acceptButton = findViewById(R.id.btn_ok);
cancelButton = findViewById(R.id.btn_cancel);
btn_gallery = findViewById(R.id.go_to_gallery);
imagePreview = findViewById(R.id.image_view_photo_preview);
...
// File name to save the picture
// First is getting the new project name from previous Activity:
String newProjName = GlobalVariables.ProjectName;
// Creating part of the name for image: timestamp. That will be: pic_tamestamp.jpeg
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("ddMMyy_HHmmss").format(new Date());
directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Captures_Camera2/Proj_" + newProjName);
GlobalVariables.MyDirectoryPath = directory.getPath();
if (!directory.exists() || !directory.isDirectory())
directory.mkdirs();
mFile = new File(directory, "pic_" + timestamp + ".jpeg");
pathToFile = mFile.getPath();
....
// ------------ GO TO GALLERY ---------
btn_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "You are going to Gallery...");
Intent GalleryIntent = new Intent(context, Gallery_Activity.class);
startActivity(GalleryIntent);
}
});
// ------------ SAVE PHOTO TO THE GALLERY ---------
acceptButton.setOnClickListener(new View.OnClickListener() {//26
#Override
public void onClick(View v) {
Toast.makeText(context, "Image saved to " + pathToFile, Toast.LENGTH_LONG).show();
// Recreating the activity with a new instance
recreate();
}
});
...
Gallery_Activity.java
public class Gallery_Activity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = "GalleryActivity";
private final Context context = this;
private ImageView imageView1, imageView2;
private final int CODE_IMAGE_GALLERY_FIRST = 1;
private final int CODE_IMAGE_GALLERY_SECOND = 2;
private final int CODE_MULTIPLE_IMAGES_GALLERY = 3;
// Variables to check the name
private String directoryPath;
private String MyPath1 = null;
private String MyPath2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Keeping the screen on even when there is no touch interaction
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_gallery);
imageView1 = findViewById(R.id.imageView1);
// If you make a short click in the ImageView, you can choose only one image, if it is long click, you can choose two images
imageView1.setOnClickListener(this);
imageView1.setOnLongClickListener(this);
imageView2 = findViewById(R.id.imageView2);
imageView2.setOnClickListener(this);
imageView2.setOnLongClickListener(this);
directoryPath = GlobalVariables.MyDirectoryPath;
Log.d(TAG, " The path from Camera_Activity is: " + directoryPath); // /storage/emulated/0/Pictures/Captures_Camera2/Proj_*
chooseMultipleImages();
}
private void chooseMultipleImages() {
// TODO: here it does NOT enter the giving folder although using the path
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting two images.."), CODE_MULTIPLE_IMAGES_GALLERY);
}
....
public void processImages(View view) {
//Toast.makeText(context, "Going to detect features...", Toast.LENGTH_SHORT).show();
Intent processIntent = new Intent(context, ImageProcessing.class);
startActivity(processIntent);
finish();
}
#Override
public boolean onLongClick(View v) {
recreate();
return false;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageView1){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting first image.."), CODE_IMAGE_GALLERY_FIRST);
}
else if(v.getId() == R.id.imageView2){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting second image.."), CODE_IMAGE_GALLERY_SECOND);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ContentResolver resolver = this.getContentResolver();
// Get data from the folder
assert data != null;
Uri MyData = data.getData(); // for simple image
ClipData MultiImg = data.getClipData(); // for multiple images
GlobalVariables.countImg = MultiImg.getItemCount();
/* ******************************************
To pick multiples images from Gallery
******************************************
*/
if (requestCode == CODE_MULTIPLE_IMAGES_GALLERY && resultCode == RESULT_OK ){
/*
// TODO: For multiple images, more than 2 change this
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();*/
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
if(GlobalVariables.countImg == 2){
// Getting name of the picture and print it
MyPath1 = MultiImg.getItemAt(0).getUri().toString();
MyPath2 = MultiImg.getItemAt(1).getUri().toString();
String Name1 = StringUtils.right(MyPath1,22);
String Name2 = StringUtils.right(MyPath2,22);
//String Proj_name = StringUtils.
GlobalVariables.PictureName1 = Name1;
GlobalVariables.PictureName2 = Name2;
Log.d(TAG, "--- First data name: " + StringUtils.right(MyPath1,22));
Log.d(TAG, "--- Second data name: " + StringUtils.right(MyPath2,22));
//Log.d(TAG, "Selected Items: " + clipData.getItemCount());
Log.d(TAG, "The full path is: " + MultiImg.getItemAt(0).getUri().toString());
// Showing images in the imageView
imageView1.setImageURI(MultiImg.getItemAt(0).getUri());
imageView2.setImageURI(MultiImg.getItemAt(1).getUri());
} else if (MyData != null ){
Log.d(TAG, "Only one image selected..");
Toast.makeText(context, "You should select 2 images and not only one", Toast.LENGTH_LONG).show();
recreate();
}
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
else if (GlobalVariables.countImg > 2){
//Log.d(TAG, "More than two selected images...");
Toast.makeText(context, "You should select 2 images and not ..." + GlobalVariables.countImg, Toast.LENGTH_LONG).show();
recreate();
}
}
/* ******************************************
To pick only one image fom Gallery for
each of ImageView and check that they
are different.
******************************************
*/
// pick image to the imageView1
else if(requestCode == CODE_IMAGE_GALLERY_FIRST && resultCode == RESULT_OK && MyData != null){
MyPath1 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView2 has an image: \n" + StringUtils.right(MyPaths2,22));
assert StringUtils.right(MyPath1, 22) != null;
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName1 = StringUtils.right(MyPath1,22);
imageView1.setImageURI(MyData);
}
}
// pick image to the imageView2
else if(requestCode == CODE_IMAGE_GALLERY_SECOND && resultCode == RESULT_OK && MyData != null) {
MyPath2 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView1 has an image: \n" + StringUtils.right(MyPaths2,22));
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName2 = StringUtils.right(MyPath2,22);
imageView2.setImageURI(MyData);
}
}
}
....
}
Can someone advise me on how I can solve this problem?
It is clear that I could leave things as they are and tell the user to check the folder where he selects the photos. But I would like it to be something more fluid and intuitive.
Thanks in advance.
private ArrayList<File> m_list = new ArrayList<File>();
String folderpath = Environment.getExternalStorageDirectory()
+ File.separator + "folder_name/";
File dir = new File(folderpath);
m_list.clear();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.getPath().contains("Not_Found"))
m_list.add(file);
}
}

Problem with sending data from BroadcastReceiver to Widget and update data on display

I have a problem, I wonder how I can send data from BroadcastReceiver(it is in Service) to widget and update widget after click button.
Specifically, I mean how to send this title song to my widget
Below is my BroadcastReciver:
private final BroadcastReceiver mWidgetEventsReceiver = new BroadcastReceiver() {
private Bundle extras;
private MediaService mService;
AppWidgetManager appWidgetManager;
private static final String TAG = "MediaMusicWidgetProvider";
#Override
public void onReceive(Context context, Intent intent) {
extras = intent.getExtras();
Log.d(TAG, extras.getString("EVENT"));
if (extras.getString("EVENT") == "NEXT") {
Log.d(TAG, "onReceive: switch");
if (mPlaybackModel != null) {
MediaItemMetadata mediaItemMetadata = mPlaybackModel.getMetadata();
if (mediaItemMetadata != null) {
MediaPlayerSong song = new MediaPlayerSong();
song.setTitle(mediaItemMetadata.getTitle() + "");
song.setDurationSec((int) (mPlaybackModel.getMaxProgress() / 1000));
song.setArtist(mediaItemMetadata.getSubtitle() + "");
song.setAlbum(mediaItemMetadata.getDescription() + "");
String title = mediaItemMetadata.getTitle()+"";
Log.d(TAG, "onReceive: "+title);
}
}
onNextTrack();
}
and there is my Provider
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, MediaMusicWidgetProvider.class);
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
log("onUpdate");
for (int appWidgetId : appWidgetIds) {
mViews = new RemoteViews(context.getPackageName(), R.layout.media_widget_blue);
appWidgetManager.updateAppWidget(appWidgetId, mViews);
}
}
#Override
public void onReceive(Context context, Intent intent) {
log("onReceive");
super.onReceive(context, intent);
if (intent.getAction() == NEXT_BUTTON) {
Toast.makeText(context, "Button next", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", NEXT_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);;
} else if (intent.getAction() == PREV_BUTTON) {
Toast.makeText(context, "Button prev", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", PREV_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);
} else if (intent.getAction() == PAUSE_BUTTON) {
Toast.makeText(context, "Button pause", Toast.LENGTH_SHORT).show();
Intent eventIntent = new Intent("com.mobica.widget.action.TEST");
eventIntent.putExtra("EVENT", PAUSE_BUTTON);
LocalBroadcastManager.getInstance(context).sendBroadcast(eventIntent);
}
}
#Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
log("onAppWidgetOptionsChanged");
mViews = new RemoteViews(context.getPackageName(), getProperLayout(context, newOptions));
mViews.setOnClickPendingIntent(mNextBtnId, getPendingSelfIntent(context, NEXT_BUTTON));
mViews.setOnClickPendingIntent(mPrevBtnId, getPendingSelfIntent(context, PREV_BUTTON));
mViews.setOnClickPendingIntent(mPauseBtnId, getPendingSelfIntent(context, PAUSE_BUTTON));
appWidgetManager.updateAppWidget(appWidgetId, mViews);
}
private int getProperLayout(Context context, Bundle newOptions) {
int maxWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
int maxHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
int minHeight = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
int minWidth = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
log("Min width: " + minWidth + "\nMax width: " + maxWidth + "\nMin height: " + minHeight + "\nMaxHeight: " + maxHeight);
boolean isLongWidget = minWidth > 460;
String currentTheme = Settings.Global.getString(context.getContentResolver(), THEME_KEY);
int properLayoutId = isLongWidget ? R.layout.media_widget_blue_long : R.layout.media_widget_blue;
if (currentTheme == null) {
return properLayoutId;
}
switch (currentTheme) {
case THEME_BLUE:
properLayoutId = isLongWidget ? R.layout.media_widget_blue_long : R.layout.media_widget_blue;
break;
case THEME_GREEN:
properLayoutId = isLongWidget ? R.layout.media_widget_green_long : R.layout.media_widget_green;
break;
case THEME_PURPLE:
properLayoutId = isLongWidget ? R.layout.media_widget_purple_long : R.layout.media_widget_purple;
break;
}
return properLayoutId;
}
}
I try do it like here https://stackoverflow.com/a/4412949/11766578 but I have problem with this line of code:
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_2x1);
like u can see above I switch layout in dependencies which color of theme user select. Please for help! :)

Alarm service notification doesn't cancel

I'm trying to build this app which checks a folder size on an interval, and if the folder size is bigger than whatever user have set, a notification appears. The problem is when user disables the notification, it still keeps on notifying ("ShowNotif" is called), what am I doing wrong?
ScheduleFragment.java
public class ScheduleFragment extends Fragment {
SharedPreferences.Editor editor;
AlarmManager manager;
PendingIntent pendingIntent;
SharedPreferences share;
EditText telegSizeText;
CheckBox telegramSize;
private boolean telegramSizeIsSet = false;
CheckBox notif;
public ScheduleFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_schedule, container, false);
telegramSize = (CheckBox)view.findViewById(R.id.telegramSize);
telegSizeText = (EditText)view.findViewById(R.id.telegSizeText);
notif = (CheckBox) view.findViewById(R.id.notif);
share = getActivity().getSharedPreferences("setting", 0);
editor = this.share.edit();
telegramSize.setChecked(share.getBoolean("telegram_selected", false));
telegramSizeIsSet = true;
int var2 = share.getInt("telegram_size", -1);
if(var2 != -1) {
telegSizeText.setText(String.valueOf(var2));
} else {
telegSizeText.setText("");
}
this.telegramSize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton var1, boolean var2) {
if (telegramSizeIsSet) {
if(!var2) {
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
Intent var11 = new Intent(getActivity(), ShowNotif.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentNoti = PendingIntent.getBroadcast(getActivity(), 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
if(telegSizeText.getText().toString() == null || telegSizeText.getText().toString().equals("")) {
Toast.makeText(getContext(), "Can't be empty", Toast.LENGTH_SHORT).show();
telegramSizeIsSet = false;
telegramSize.setChecked(false);
telegramSizeIsSet = true;
return;
}
Intent var9 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, var9, 0);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
editor.putInt("telegram_size", Integer.valueOf(telegSizeText.getText().toString()).intValue());
editor.putBoolean("telegram_selected", true);
editor.commit();
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
manager.setRepeating(0, System.currentTimeMillis(), (long) 10000, pendingIntent); //check every 10 seconds
Toast.makeText(getContext(), "Enabled!", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}}
CheckTelegramSizeReceiver.java
public class CheckTelegramSizeReceiver extends BroadcastReceiver {
private AlarmManager manager;
private AlarmManager manager2;
private AlarmManager manager3;
private boolean notificationCanceled;
boolean notificationCreated = false;
String path;
private PendingIntent pendingIntent;
private PendingIntent pendingIntent2;
long totalSizes = 0L;
int userSelectedSize = 0;
private long getFileSize(String var1) {
long var2 = 0L;
File[] var4 = (new File(var1)).listFiles();
if (var4 != null) {
for (int var5 = 0; var5 < var4.length; ++var5) {
File var6 = var4[var5];
if (var6.isDirectory()) {
var2 += this.getFileSize(var6.getPath());
} else {
var2 += var6.length();
}
}
}
return var2;
}
public void onReceive(final Context var1, Intent var2) {
File var3 = Environment.getExternalStorageDirectory();
this.path = var3 + "/Telegram";
(new AsyncTask<Void, Integer, Integer>() {
protected Integer doInBackground(Void... var1x) {
totalSizes = getFileSize(path) / 1048576L;
//
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
userSelectedSize = var2.getInt("telegram_size", -1);
return 1;
}
protected void onPostExecute(Integer var1x) {
SharedPreferences var2 = var1.getSharedPreferences("setting", 0);
Editor var3 = var2.edit();
CheckTelegramSizeReceiver.this.userSelectedSize = var2.getInt("telegram_size", -1);
CheckTelegramSizeReceiver.this.notificationCreated = var2.getBoolean("notificationIsShowing", false);
CheckTelegramSizeReceiver.this.notificationCanceled = var2.getBoolean("notificationIsShowingCanceled", false);
if ((int) CheckTelegramSizeReceiver.this.totalSizes > CheckTelegramSizeReceiver.this.userSelectedSize && !CheckTelegramSizeReceiver.this.notificationCreated) {
Intent var11 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var11, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.setRepeating(0, System.currentTimeMillis(), (long) 28800000, CheckTelegramSizeReceiver.this.pendingIntent);
var3.putBoolean("notificationIsShowing", true).commit();
var3.putBoolean("notificationIsShowingCanceled", false).commit();
CheckTelegramSizeReceiver.this.notificationCreated = true;
CheckTelegramSizeReceiver.this.notificationCanceled = false;
}
if ((int) CheckTelegramSizeReceiver.this.totalSizes < CheckTelegramSizeReceiver.this.userSelectedSize && CheckTelegramSizeReceiver.this.notificationCreated && !CheckTelegramSizeReceiver.this.notificationCanceled) {
System.out.println("test");
Intent var5 = new Intent(var1, ShowNotif.class);
CheckTelegramSizeReceiver.this.pendingIntent = PendingIntent.getBroadcast(var1, 1, var5, 0);
CheckTelegramSizeReceiver.this.manager2 = (AlarmManager) var1.getSystemService(Context.ALARM_SERVICE);
CheckTelegramSizeReceiver.this.manager2.cancel(CheckTelegramSizeReceiver.this.pendingIntent);
CheckTelegramSizeReceiver.this.notificationCreated = false;
CheckTelegramSizeReceiver.this.notificationCanceled = true;
var3.putBoolean("notificationIsShowingCanceled", true).commit();
var3.putBoolean("notificationIsShowing", false).commit();
}
}
}).execute(null, null, null);
}}
ShowNotif.java
public class ShowNotif extends BroadcastReceiver {
public void onReceive(Context var1, Intent var2) {
int var3 = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
if (var3 <= 22 && var3 >= 10) {
Uri var4 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap var5 = BitmapFactory.decodeResource(var1.getResources(), R.drawable.icon_notif);
NotificationCompat.Builder var6 = (new NotificationCompat.Builder(var1)).setSmallIcon(R.drawable.icon_notif).setLargeIcon(var5).setContentTitle("My App").setContentText("Notification Text").setSound(var4).setAutoCancel(true);
var6.setContentIntent(PendingIntent.getActivity(var1, 0, new Intent(var1, MainActivity.class), 0));
((NotificationManager) var1.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, var6.build());
}
}}
Thanks in advance.
if (telegramSizeIsSet) {
if(!var2) {
Intent var3 = new Intent(getActivity(), CheckTelegramSizeReceiver.class);
manager = (AlarmManager)getContext().getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(var1, 1,var11,PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntentNoti = PendingIntent.getBroadcast(var1, 1, var11,PendingIntent.FLAG_UPDATE_CURRENT);
manager.cancel(pendingIntent);
manager.cancel(pendingIntentNoti);
Toast.makeText(getContext(), "Disabled!", Toast.LENGTH_SHORT).show();
editor.putBoolean("telegram_selected", false);
editor.putInt("telegram_size", -1);
telegSizeText.setText("");
editor.commit();
return;
}
Basically you just cancel the Alarm for CheckTelegramSizeReceiver receiver. but you forget to cancel the alarm set up by CheckTelegramSizeReceiver receiver that is ShowNoti Receiver. So ShowNoti receiver shows the notification again and again so you need to cancel the ShowNoti alaram too and use FLAG_UPDATE_CURRENT instead of 0. Thanks It may help you!

Why the name in listView keep changing?

I have a listView in Activity A as shown below. All the values and name were actually returned from Activity C to B then only A.
When the first list is clicked, it should display text Project and value 3 on editText B. But it displays Medical which was actually getting from the last list.
After I change the value from 3 to 43 and return to A, the name changed. What should I do so that the name will remain the same ?
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if list clicked
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true); // image
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}
}
});
return claims;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1) { // if is icon button clicked
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // for Medical
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
// m_listItems.clear();
if (mClickedPosition==-1)
{
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
Activity B (Project1)
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Noted that the result in Activity A represents value 3,5 while name represents project and Medical. How can I fix this ? Please help.
From what I understood, your variable name in Activity A contains previously resulted value (from Activity B) and not from row you have clicked on listview i.e. "Medical" value you previously got from Activity B which held by variable name and on your listview click event you have checks the if name is "Medical" or "Project" (and in this case it is "Medical" and hence Medical activity is started).
One solution is to get the value("Project/Medical") from listview.
Try this code.
Activity A
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
name = temp[1].trim();
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}

Android in app Billing to Unlock all Features

I followed a guide to enter the in app purchase and unlock all features. The procedure to purchase works well.
I explain what I do: I added a check in my database, which counts the number of records in a table, if the number is> = 1, I open an activity for purchase in the app. Once purchased, through the method getPurchases, control the purchase, if it was done I open the activity, otherwise I open the activity for purchase. I created this code peril control but I get error:
08-11 18:08:18.120: W/ContextImpl(19293): Implicit intents with startService
are not safe: Intent {
act=com.android.vending.billing.InAppBillingService.BIND }
android.content.ContextWrapper.bindService:529
main.Elenco_F_Fragment.Controlla_record_per_acquisto:243
main.Elenco_F_Fragment.access$9:233
this is the row 243:
final boolean blnBind = getActivity().bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
this is the code for the control
private void Controlla_record_per_acquisto(){
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String controllo = "SELECT COUNT(_id) FROM tbf";
Cursor c = db.rawQuery(controllo, null);
while (c.moveToNext()){
int numero_id = c.getInt(0);
if(numero_id >=1){
// Bind Service
final boolean blnBind = getActivity().bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
if (!blnBind) return;
if (mService == null) return;
Bundle ownedItems;
try {
ownedItems = mService.getPurchases(3, getActivity().getPackageName(), "inapp", null);
Intent intent = null;
intent = new Intent(getActivity(), Crea_e.class);
startActivity(intent);
} catch (RemoteException e) {
e.printStackTrace();
Toast.makeText(context, "getPurchases - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "getPurchases() - fail!");
return;
}
int response = ownedItems.getInt("RESPONSE_CODE");
Toast.makeText(context, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response), Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response));
if (response != 0) return;
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_ITEM_LIST\" return " + ownedSkus.toString());
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_DATA_LIST\" return " + purchaseDataList.toString());
Log.i(tag, "getPurchases() - \"INAPP_DATA_SIGNATURE\" return " + (signatureList != null ? signatureList.toString() : "null"));
Log.i(tag, "getPurchases() - \"INAPP_CONTINUATION_TOKEN\" return " + (continuationToken != null ? continuationToken : "null"));
}else {
Intent intent = null;
intent = new Intent(getActivity(), InAppBillingActivity.class);
startActivity(intent);
}
c.close();
db.close();
}
}
EDIT--------------------------------------------
private void Controlla_record_per_acquisto(){
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String controllo = "SELECT COUNT(_id) FROM FTB";
Cursor c = db.rawQuery(controllo, null);
while (c.moveToNext()){
int numero_id = c.getInt(0);
if(numero_id >=1){
Intent intent = null;
intent = new Intent(getActivity(), InAppBillingActivity.class);
startActivity(intent);
}else {
Intent intent = null;
intent = new Intent(getActivity(), Cure.class);
startActivity(intent);
}
c.close();
db.close();
}
}
I would suggest you to use the new Billing system, with the IabHelper class there you can do what you have described above both async/sync without the needs for "extra" code really.
http://developer.android.com/training/in-app-billing/preparing-iab-app.html

Categories