package com.example.myapplication;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.schema.Model;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class MainActivity extends AppCompatActivity {
TextView result, confidence;
ImageView imageView;
Button picture;
int imageSize = 224;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.result);
confidence = findViewById(R.id.confidence);
imageView = findViewById(R.id.imageView);
picture = findViewById(R.id.button);
picture.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
// Launch camera if we have permission
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
} else {
//Request camera permission if we don't have it.
requestPermissions(new String[]{Manifest.permission.CAMERA}, 100);
}
}
});
}
public void classifyImage(Bitmap image){
try {
Model model = Model.newInstance(getApplicationContext());
//creates inputs for reference.
TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 224, 224, 3}, DataType.FLOAT32);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4* imageSize * imageSize * 5);
byteBuffer.order(ByteOrder.nativeOrder());
int [] intValues = new int[imageSize * imageSize];
image.getPixels(intValues, 0, image.getWidth(),0,0, image.getWidth(), image.getHeight());
int pixel = 0;
for(int i = 0; i < imageSize; i++){
for(int j = 0; j< imageSize; j++){
int val = intValues[pixel++]; //RGB
byteBuffer.putFloat(((val>> 16) & 0xFF) * (1.f/255.f));
byteBuffer.putFloat(((val>> 8) & 0xFF) * (1.f/255.f));
byteBuffer.putFloat((val & 0xFF) * (1.f/255.f));
}
}
inputFeature0.loadBuffer(byteBuffer);
//Runs model inference and gets result.
Model.Outputs outputs = model.process(inputFeature0);
TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();
float[] confidence = outputFeature0.getFloatArray();
//Release model resources if no longer used.
model.close();
}catch (IOException e) {
//TODO Handle the exception
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
int dimension = Math.min(image.getWidth(), image.getHeight());
image = ThumbnailUtils.extractThumbnail(image, dimension, dimension);
imageView.setImageBitmap(image);
image = Bitmap.createScaledBitmap(image, imageSize, imageSize, false);
classifyImage(image);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
I am making an app in android studio. My app includes tensorflow lite. I refer to this youtube video https://www.youtube.com/watch?v=jhGm4KDafKU
But I got similar problems. This is the picture that shows problems. In image, all problems is about 'can not resolve method or symbol' .
So I found these in google but I can't understand anything. I mean I'm just following the youtube... Guys... Can you explain the meaning of 'cannot resolve method or symbol'? Can you show me what I have to write and where to put. According to explaining maybe I miss import function but how do I do it..?
Related
save last position of videoView saved by sharedprefrence and start in last position (android studio)
hello I serch for my problam in stackaverflow and other refrences but I dont get my answer
.
I use VideoView In my app
I want to save the last position of videview in a sharedPrefrence to start again from the last position but it start in 0 every time
please check my code and tel me what should i do.
package com.rewass.qurankurdishaudiotranslatev2.activitys;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.rewass.qurankurdishaudiotranslatev2.R;
import com.rewass.qurankurdishaudiotranslatev2.adapters.RecyclerViewAdapter;
import com.rewass.qurankurdishaudiotranslatev2.model.ModelRecycler;
import com.rewass.qurankurdishaudiotranslatev2.text.Text002;
import java.util.ArrayList;
import java.util.List;
public class A002 extends AppCompatActivity {
List<ModelRecycler> listItems;
private InterstitialAd mInterstitialAd;
String AudioURL = "https://download.quranicaudio.com/quran/mishaari_raashid_al_3afaasee/002.mp3";
VideoView videoView;
ProgressBar progressBar008;
TextView te008;
int progress;
RecyclerView myrv;
String kurdish002 = "http://sirwaan.com/aaap/audios/kurdish/sound/quran/qurankurdish/002.mp3";
String v2kurdish002 = "https://sirwaan.com/aaap/audios/kurdish/sound/quran/newversionqurankurdish/002.mp3";
Handler handler;
GridLayoutManager layoutManager;
int seekkk;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a002);
audioSora();
}
SharedPreferences preferences ;
private void audioSora() {
preferences = getSharedPreferences("pref55",MODE_PRIVATE);
videoView = findViewById(R.id.videoview002);
videoView.setVideoPath(v2kurdish002);
//control media
MediaController mediaController = new MediaController(this);
//set view with controller
videoView.setMediaController(mediaController);
//set Controller to view
mediaController.setAnchorView(videoView);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
SharedPreferences.Editor editor = preferences.edit();
int progress = videoView.getCurrentPosition();
editor.putInt("seekto", progress);
editor.apply();
seekkk = preferences.getInt("seekto", 0);
Toast.makeText(A002.this, seekkk+"", Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 1000); }};
handler.postDelayed(r, 1000);
videoView.seekTo(seekkk);
videoView.start();
}
});
}
}
private int time = 0;
private ScheduledExecutorService mScheduledExecutorService;
Runnable getPositionVideo = () -> {
time = binding.epVideoView.getCurrentPosition();
Log.d(TAG, ": " + time);
};
binding.epVideoView.setOnPreparedListener(mediaPlayer -> {
mediaController.setAnchorView(binding.epVideoView);
binding.epVideoView.start();
mScheduledExecutorService = new ScheduledThreadPoolExecutor(1);
mScheduledExecutorService.scheduleWithFixedDelay(() -> {
runOnUiThread(getPositionVideo);
MediaControllerCustom.init(url, time);
}, 1000, 1000, TimeUnit.MILLISECONDS);
});
I have been trying to run two tasks on two threads and using their progress to be indicated on progress bar and progress indicator.
First task is copyTask and second is copy file.
The copyTask sends the file object to copyFile for file copy.
But the problem is only a single file gets copied and the file count seems to be correct.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.CountDownLatch;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
/**
* FXML Controller class
*
* #author ANIL
*/
public class ProgressIndicateController implements Initializable {
#FXML
private ProgressIndicator uploadIndicator;
#FXML
private ProgressBar uploadBar;
#FXML
private TextArea errTxt;
#FXML
private Label uploadTxt;
File f;
Thread parent,child;
CountDownLatch latch = new CountDownLatch(1);
#FXML
private Label sizeTXT;
// private CopyTask copyTask;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
// Unbind progress property
uploadBar.progressProperty().unbind();
// Bind progress property
uploadBar.progressProperty().bind(copyFile.progressProperty());
// Hủy bỏ kết nối thuộc tính progress
uploadIndicator.progressProperty().unbind();
// Bind progress property.
uploadIndicator.progressProperty().bind(copyTask.progressProperty());
// Unbind text property for Label.
uploadTxt.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
uploadTxt.textProperty().bind(copyTask.messageProperty());
// Unbind text property for Label.
sizeTXT.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
sizeTXT.textProperty().bind(copyFile.messageProperty());
// When completed tasks
copyTask.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
List<File> copied = copyTask.getValue();
uploadTxt.textProperty().unbind();
uploadTxt.setText("Copied: " + copied.size());
}
});
copyFile.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
File copied = copyFile.getValue();
sizeTXT.textProperty().unbind();
sizeTXT.setText("Copied: " + copied.getAbsolutePath());
}
});
// Start the Task.
parent= new Thread(copyTask);
parent.start();
}
Task<List<File>> copyTask = new Task<List<File>>() {
#Override
protected List<File> call() throws Exception {
File dir = new File("F:");
File[] files = dir.listFiles();
int count = files.length;
List<File> copied = new ArrayList<File>();
int i = 0;
for (File file : files) {
if (file.isFile()) {
this.copy(file);
copied.add(file);
}
i++;
this.updateProgress(i, count);
}
return copied;
}
private void copy(File file) throws Exception {
this.updateMessage("Copying: " + file.getAbsolutePath());
f = file;
child=new Thread(copyFile);
child.start();
this.wait();
}
};
Task<File> copyFile = new Task<File>() {
#Override
protected File call() throws Exception {
InputStream is = null;
OutputStream os = null;
File dest=null;
String name=f.getName();
dest=new File("D:\\OUTPUT\\"+name);
is = new FileInputStream(f);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
double i=0.0;
double l=f.length();
while ((length = is.read(buffer)) > 0) {
i+=length;
this.updateMessage("Copying: " + i +" bytes of " + l);
os.write(buffer, 0, length);
this.updateProgress(i, l);
Thread.sleep(500);
}
is.close();
os.close();
this.notifyAll();
return dest;
}
};
}
New Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CyclicBarrier;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
/**
* FXML Controller class
*
* #author ANIL
*/
public class ProgressIndicateController implements Initializable {
#FXML
private ProgressIndicator uploadIndicator;
#FXML
private ProgressBar uploadBar;
#FXML
private TextArea errTxt;
#FXML
private Label uploadTxt;
#FXML
private Label sizeTXT;
CyclicBarrier cb = new CyclicBarrier(2);
final SimpleDoubleProperty prog1 = new SimpleDoubleProperty(0);
final SimpleDoubleProperty prog2 = new SimpleDoubleProperty(0);
final SimpleStringProperty text1 = new SimpleStringProperty("");
final SimpleStringProperty text2 = new SimpleStringProperty("");
final SimpleStringProperty err = new SimpleStringProperty("");
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
// Unbind progress property
uploadBar.progressProperty().unbind();
// Bind progress property
uploadBar.progressProperty().bind(prog2);
// Hủy bỏ kết nối thuộc tính progress
uploadIndicator.progressProperty().unbind();
// Bind progress property.
uploadIndicator.progressProperty().bind(prog1);
// Unbind text property for Label.
uploadTxt.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
uploadTxt.textProperty().bind(text1);
// Unbind text property for Label.
sizeTXT.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
sizeTXT.textProperty().bind(text2);
//When completed tasks
errTxt.textProperty().unbind();
errTxt.textProperty().bind(err);
// Start the Task.
new Thread() {
#Override
public void run() {
File dir = new File("F:");
File[] files = dir.listFiles();
int count = files.length;
int i = 0;
for (File file : files) {
if (file.isFile()) {
try {
text1.setValue("Copying: " + file.getAbsolutePath());
InputStream is = null;
OutputStream os = null;
File dest = null;
String name = file.getName();
dest = new File("D:\\OUTPUT\\" + name);
is = new FileInputStream(file);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
double j = 0.0;
double l = file.length();
while ((length = is.read(buffer)) > 0) {
j += length;
text2.setValue("Copying: " + j + " bytes of " + l);
os.write(buffer, 0, length);
prog2.setValue(j / l);
Thread.sleep(100);
}
is.close();
os.close();
} catch (Exception ex) {
err.setValue(ex.toString());
}
i++;
prog1.setValue(i / count);
}
}
}
}.start();
}
}
I'm having issues to render a SVG Image in a TableView with a CellFactory.
Im using this code here, but it don't work, the svg image is scaled, but it don't resize.
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.shape.SVGPath;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class SVGTable extends Application {
private ObservableList<SVGExample> examples;
public static void main(String[] args) {
launch(args);
}
public SVGTable() {
examples = FXCollections.observableArrayList();
examples.addAll(new SVGExample(289),
new SVGExample(42),
new SVGExample(120));
}
#Override
public void start(Stage primaryStage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
TableView<SVGExample> tableView = new TableView<>();
tableView.setMinWidth(500);
tableView.setMinHeight(400);
tableView.setItems(examples);
final TableColumn<SVGExample, Integer> ping = new TableColumn<>("Ping");
ping.setCellValueFactory(new PropertyValueFactory<>("ping"));
ping.setCellFactory(param -> new PingCell());
tableView.getColumns().add(ping);
pane.getChildren().add(tableView);
primaryStage.setScene(scene);
primaryStage.show();
}
public class SVGExample {
private final IntegerProperty ping = new SimpleIntegerProperty();
public SVGExample(int ping) {
setPing(ping);
}
public int getPing() {
return ping.get();
}
public IntegerProperty pingProperty() {
return ping;
}
public void setPing(int ping) {
this.ping.set(ping);
}
}
public class PingCell extends TableCell<SVGExample, Integer> {
private HBox hBox = new HBox();
private Label label;
private int oldValue;
private PingCell() {
label = new Label();
hBox.setAlignment(Pos.CENTER_LEFT);
oldValue = Integer.MIN_VALUE;
}
#Override
protected void updateItem(final Integer item, final boolean empty) {
if (item != null) {
label.setText(item + "ms");
int i = (item + 50) / 100;
if (i < 1)
i = 1;
if (4 < i)
i = 4;
if (i != oldValue) {
SVGPath svgPath1 = new SVGPath();
svgPath1.setContent("M149.2,8.3L127-13.9c42.4-42.4,98.7-65.8,158.5-65.8c59.8,0,116.1,23.4,158.5,65.8L421.8,8.3c-36.5-36.5-84.9-56.6-136.3-56.6C234.1-48.2,185.7-28.1,149.2,8.3z");
SVGPath svgPath2 = new SVGPath();
svgPath2.setContent("M190.9,50.1l-22.2-22.2C200-3.4,241.4-20.6,285.5-20.6c44.1,0,85.5,17.2,116.8,48.4l-22.2,22.2c-25.3-25.3-58.9-39.2-94.6-39.2C249.8,10.8,216.2,24.8,190.9,50.1z");
SVGPath svgPath3 = new SVGPath();
svgPath3.setContent("M232.7,91.8l-22.2-22.2c20.1-20.1,46.7-31.1,75-31.1s55,11.1,75,31.1l-22.2,22.2c-14.1-14.1-32.9-21.9-52.8-21.9C265.6,69.9,246.8,77.7,232.7,91.8z");
SVGPath svgPath4 = new SVGPath();
svgPath4.setContent("M285.5,98.1c-12.8,0-24.5,5.2-32.9,13.6l32.9,32.9l32.9-32.9C310,103.3,298.3,98.1,285.5,98.1z");
Shape s = SVGPath.union(SVGPath.union(SVGPath.union(svgPath1, svgPath2), svgPath3), svgPath4);
s.setScaleX(0.1);
s.setScaleY(0.1);
hBox.getChildren().clear();
hBox.getChildren().addAll(s, label);
}
setGraphic(hBox);
}
}
}
}
After run, it's look like this:
You can wrap the Shape in a Group to force re-size of layout bounds.
hBox.getChildren().addAll(new Group(s), label);
Scale is a type of transform and according to Javadocs:
Any transform, effect, or state applied to a Group will be applied to all children of that group. Such transforms and effects will NOT be included in this Group's layout bounds, however if transforms and effects are set directly on children of this Group, those will be included in this Group's layout bounds.
I'm a beginner to android studio. I'm trying to build an my project app that can send my location to another client with just one click. i.e through online server.
At first I'm trying to test if my button gets the latitude and longitude value from the LocationListener.
below is my mainActivity
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private String myLoc = " ";
GoogleMap mMap;
Button bShare;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final double Shillong_Lat = 25.5667,
Shillong_Lng = 91.8833;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1000, this);
if (servicesOK() ){
setContentView(R.layout.activity_map);
bShare = (Button) findViewById(R.id.bShare);
bShare.setOnClickListener(this);
if(initMap()) {
Toast.makeText(MainActivity.this, "Ready to map", Toast.LENGTH_SHORT).show();
gotoLocation(Shillong_Lat, Shillong_Lng, 15 );
mMap.setMyLocationEnabled(true);
}else{
Toast.makeText(this, "Map not Connected!", Toast.LENGTH_SHORT).show();
}
}else {
setContentView(R.layout.activity_main);
}
}
private void gotoLocation(double latitude, double longitude, float zoom) {
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
}else {
Toast.makeText(this, "Can't connect to map", Toast.LENGTH_SHORT).show();
}return false;
}
private boolean initMap() {
if (mMap == null){
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
}
return(mMap != null);
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity.this, "Location changed: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myLoc = GetAddressDetailed(latitude, longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bShare){
Toast.makeText(MainActivity.this, "Sent: " + myLat + ", " + myLon ,Toast.LENGTH_SHORT).show();
}
}
}
hiii
I am new to to android.I have created a calender where I am able to set alarm.
But the problem is I am unable to receive any message i.e if i set an alarm of 2.30pm,A message should appear that alarm received.I am not receiving this message ..Please suggest..
Please help
Here is the code...
alarm.java
package com.example.notificationalarm;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class Alarm extends ActionBarActivity
{
TimePicker myTimePicker;
Button buttonstartSetDialog;
TextView textAlarmPrompt;
TimePickerDialog timePickerDialog;
final static int RQS_1 = 1;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
textAlarmPrompt=(TextView)findViewById(R.id.alarm);
buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
textAlarmPrompt.setText("");
openTimePickerDialog(false);
}
});
}
private void openTimePickerDialog(boolean is24r){
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
Alarm.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
OnTimeSetListener onTimeSetListener= new OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar targetCal){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
}
AlarmReceiver .java
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
}
}
How have you declared your AlarmManager in the Manifest?
When I look on the code I cannot find any bug, so let's try this in your manifest.xml
<receiver
android:name="your.package.AlarmReceiver"/>
This might help