Hello guys. I'm making an app, its a kind of alarm scheduler but I have a problem with the code. Thats what im using
Code:
ScheduledThreadPoolExecutor scheduler=new ScheduledThreadPoolExecutor(1);
scheduler.schedule(new Runnable() {
public void run(){
alarm(1);
} }, delay , TimeUnit.SECONDS);
It works for low values of "delay" if I put a high value (11000 for example) and leave the device alone, I think it enters in sleep mode and dont execute the timer.
How can I solve that?
Thanks in advance
I dont know about the scheduler but an alarm manager can wake the phone from sleep if you want. Or run the alarm in the background while asleep
From something awesome
Thanks for your answer, worked for me.
Here's the code, it maybe help others
MainUI.java:
Code:
public class MainUI extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView boton =(TextView)findViewById(R.id.botonAplicar);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainUI.this, WakeUpReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainUI.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
int delay=1;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, delay);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.i("Test","Programmed");
}
});
}
}
WakeUpReceiver.java:
Code:
public class WakeUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Test","Wake Up Received");
}
}
Manifest:
Code:
<receiver android:process=":remote" android:name="WakeUpReceiver"></receiver>
Related
I have the menu with 2 options, settings and cancel. The setting will direct to the setting page. Here is the code I wrote so far.
Code:
static final private int SETTINGS = Menu.FIRST;
static final private int CANCEL = Menu.FIRST + 1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create and add new menu items.
MenuItem itemSet = menu.add(0, SETTINGS, Menu.NONE, "Settings");
MenuItem itemCan = menu.add(0, CANCEL, Menu.NONE, "Cancel");
// Assign icons
itemSet.setIcon(android.R.drawable.ic_menu_preferences);
itemCan.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if (item.getItemId()== SETTINGS){
Intent settingIntent = new Intent(this, setting.class);
startActivityForResult(settingIntent, 0);
}
else if (item.getItemId()== CANCEL){
//do nothing
}
return true;
}
the setting class is
Code:
public class setting extends Activity{
private Button browseButton;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
browseButton = (Button) findViewById(R.id.Btn_Browse);
browseButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent fcIntent = new Intent(v.getContext(), filechooser.class);
startActivityForResult(fcIntent, 0);
}
});
}
}
However, I got an error which is about the program stopped unexpectedly....
could anyone advices me where my program get wrong?
Thank you.
Hi guys i am new to programming. I am trying to have multiple button to send different predefined SMS to predefined number. I am not sure how to have multiple setOnClickListener(new OnClickListener() as the 2nd setOnClickListener(new OnClickListener() gave me error.
public class SendSMSActivity extends Activity {
Button buttonSend;
Button buttonSend2;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend2 = (Button) findViewById(R.id.buttonSend2);
buttonSend.setOnClickListener(new OnClickListener() {
buttonSend2.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "abc");
sendIntent.putExtra("address", "9909990");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
break;
case R.id.buttonSend2:
Intent sendIntent1 = new Intent(Intent.ACTION_VIEW);
sendIntent1.putExtra("sms_body", "def");
sendIntent1.putExtra("address", "012345678");
sendIntent1.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent1);
break;
}
}
});
});
}
}
@stewypost
You cant write statements anywhere inside an anonymous inner class anyways ignoring the poor syntax
To do this first declare your
OnClickListner listner = (View v) ->
{
// your code
};
then call
button1.setOnClickListener(listner);
button2.setOnClickListener(listner);
Sent from my GT-S5302 using Tapatalk 2
Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.
I have written the following code to allow user to display in chinese or english language. But when I select the language in the settings. There is no response and change in the App. I would like to ask if anyone could see the problems. Thank you for your help!
I have created the following folders
- values-en
- values-rTW
- values-rCN
Code:
public class AppPrefActivity extends Activity {
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
SharedPreferences pref;
public static final String PREF_LANGUAGE = "language_pref";
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragement()).commit();
}
public static class PrefsFragement extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(PREF_LANGUAGE))
{
Preference connectionPref = findPreference(key);
connectionPref.setSummary(sharedPreferences.getString(key, ""));
changeLanguagePref(sharedPreferences.getString(key, ""));
}
}
private void changeLanguagePref(String lang){
Locale locale = null;
if (lang.equals("Traditional Chinese")){
locale = new Locale("zh_rTW");
}else if (lang.equals("Simplified Chinese")){
locale = new Locale("zh_rCN");
}else{
locale = new Locale("en");
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
this.getResources().updateConfiguration(config, null);
}
}
}
This is part of the xml for language selection
Code:
<PreferenceCategory android:title="@string/pref_cat_app">
<ListPreference
android:title="@string/pref_def_lang"
android:entries="@array/app_language"
android:entryValues="@array/app_language"
android:defaultValue="English"
android:key="language_pref"/>
you need to recreate the activity after you reload all the resources.
In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.