I'm trying to make a timer for the android app I'm developing and am trying to make a test timer that will display the time left. I have tried a lot of websites but none work. Here is the complete code from the activity:
package com.hunter.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class Settings extends Activity {
//intent to return to menu from settings
public void back (View view) {
Intent back = new Intent(this, MainActivity.class);
startActivity(back);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//calls on textview
final TextView text1 = (TextView)findViewById(R.id.textView1);
//length of timer
new CountDownTimer(30000, 1000) {
//counts the milliseconds
public void onTick(long millisUntilFinished) {
//displays seconds remaining
text1.setText("seconds remaining: " + millisUntilFinished / 1000);
}
//displays when timer finishes
public void onFinish() {
text1.setText("done!");
} //<================================== error
this.start();
} //<============================== error
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The "start" call needs to be made on the object instance as follows:
(new CountDownTimer(30000, 1000) {
// your code here..
}).start();
In you code, the "this.start()" is within the class definition. It is not within any method.
Note that the "(" and ")" I have included are optional. I prefer to add them for clarity so that the object instance itself is contained. You could however do the following:
new CountDownTimer(30000, 1000) {
// your code here...
}.start();
Related
I'm a android self learner. I want to generate vibration for binary string.
Here is the code I used
import android.content.Intent;
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;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnVibrate=(Button)findViewById(R.id.btnsum);
// Set on click listener and start vibrate service when clicked on Button Vibrate
btnVibrate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// Create a New Intent and start the service
Intent intentVibrate =new Intent(getApplicationContext(),VIBRATOR_SERVICE.getClass());
startService(intentVibrate);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I want to generate vibration according to a binary string.If i give like '110' a particular vibration should generate for that string..
Thanks in advance.
You can split your string into an array
char[] charPattern = yourString.toCharArray();
Then convert your char array into a long array:
long[] pattern = new long[charPattern.length];
for (int i = 0; i < charPattern.length; i++) {
long[i] = char[i] = Long.valueOf(char[i])
}
And use your array in the vibrator.
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(pattern, 1);
Whenever Main_Activity is created then service also created but no previous service finishes I Want to finish old service whenever new service is created
This My Main Class Where I call My Service Whenever Main Activity is created
Main_Activity Class
package com.example.pushtrial;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy()
{
super.onDestroy();
//stopService(this.getIntent());
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Service Class :
package com.example.pushtrial;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onStart(Intent intent, int startid) {
Log.d(TAG, "onStart");
//new Timer().schedule(func(), "5000");// 24 hours ----> 86400
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
Log.d(TAG, "seconds remaining: " + millisUntilFinished / 1000);
//mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
Log.d(TAG, "Done!");
func();
}
}.start();
//new Timer().schedule(func(),120000);
//player.start();
}
public void func()
{
Intent myIntent = new Intent(this, SecondActivity.class);//MainActivity.class
myIntent.putExtra("FromNotification", true);
PendingIntent myPendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);
Notification myNotification = new Notification.Builder(this)
.setContentTitle("Event App")
.setContentText("Hey, [Event App] is missing you! Got a minute?")
.setSmallIcon(R.drawable.icon)
.setContentIntent(myPendingIntent)
.setAutoCancel(true)
.build();//.addAction(R.drawable.icon, "Start Service", null)myPendingIntent
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, myNotification);
}
}
SecondActivity.class
package com.example.pushtrial;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As #pskink says, you don't have 2 instances of MyService. What happens is that onStart() is called multiple times on the same instance.
If you want to prevent having multiple CountDownTimers running in parallel, then you will need to add code to your Service to keep track of the current running CountDownTimer and either kill it and start a new one, or ignore a second request to start one if there is already one running.
I'm making my first app in Android Studio. I got this activity, where it just plays a sound with MediaPlayer, and then it is supposed to return to the main activity, either by a button (works fine) or when the sound stops(what i'm missing). Is there an easy way to check if the sound has stopped playing, and then let that trigger an action?
Here is my code so far:
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class image_button_2 extends ActionBarActivity implements View.OnClickListener {
ImageButton imageButton6;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_button_2);
imageButton6 = (ImageButton) findViewById(R.id.imageButton6);
imageButton6.setOnClickListener(this);
mySound = MediaPlayer.create(this, R.raw.hb);
mySound.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_button_2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void imageButton6Click(){
mySound.stop();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.imageButton6:
imageButton6Click();
break;
}
}
}
Try this out , This will take you into MainActivity when music is finished
mySound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
imageButton6Click();
}
});
I think you are looking for OnCompletionListener callback.
i am trying to make a note app.in an array i want to make id´s.
i want to check the id with an onclicklistener.
in the onclicklistener i make an Intent and an ExtraString
in this Extrastring i want to write the content from the note file i created
this is the code :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NotizOeffnungsMenue extends Activity implements View.OnClickListener {
Button[] NoteListBtn ;
String[] NoteList ;
int [] e;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notiz_oeffnungs_menue);
LinearLayout l1 = (LinearLayout)findViewById(R.id.layout1);
NoteListBtn = new Button[fileList().length];
NoteList = fileList();
i = 0;
while (i < fileList().length)
{
NoteListBtn[i] = new Button(this);
NoteListBtn[i].setText(NoteList[i]);
NoteListBtn[i].setOnClickListener(this);
l1.addView(NoteListBtn[i]);
NoteListBtn[i].setId(i);
e [i] =i;
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.notiz_oeffnungs_menue, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view)
{
if(e[] == view.getId())
{
Intent switchintent = new Intent(this,NotizActivity.class);
String EXTRA_INHALT;
startActivity(switchintent);
}
}
}
In onClick() I would recommend u to use switch case statement
switch(v.getId()){
case R.id.butnid:
//do something here
break;
case R.id.butnid2:
//do something here
break;
}
Make as many cases as u want.
And remember that the buttons u use should do this
butnid.setOnClickListener(this);
butnid2.setOnClickListener(this);
//And so on for ever id u use in on click
You can use like this:
#Override
public void onClick(View view)
{
Intent switchintent = new Intent(this,NotizActivity.class);
switchintent.putExtra("EXTRA_INHALT", e[view.getId()]);
switchintent.putExtra("EXTRA_INHALT2", NoteList[view.getId()]);
startActivity(switchintent);
}
Instead of comparing id, you can use that as a position. Because you are already setting that position as Id.
Hope this helps.
I am trying to make a loop in Android app which is triggered by a button click.
After reading tips on making loops/delays on SO ( for example here), I decided to use message handler approach instead of Runnable.
In the code below, toastLoop() is executed and it prints "starting in x" seconds.
However, the message does not seem to be posted with that delay.
Or, the message is posted but the handler does not receive it.
I am a newbie and I am probably making a silly mistake somewhere.
What am I missing in the code below? Or is this code totally stupid?
package com.example.testapp;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class ExecActivity extends FragmentActivity {
static Context context = null;
String LOG_TAG = "FTR";
static boolean test_status = false;
ToastLoop toast_loop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exec);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.exec, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
class ToastLoop {
private final int loop_max_duration = 60; // in seconds
final int TOAST = 1;
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i(LOG_TAG, "Handler(): msg: " + msg.what);
switch (msg.what) {
case TOAST:
Toast.makeText( ExecActivity.this, "Doing my thing", Toast.LENGTH_SHORT).show();
if ( test_status) { // test is still running
toastLoop();
}
break;
default:
Toast.makeText(ExecActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
break;
}
}
};
public boolean toastLoop() {
if ( test_status) { // test is still running
long curr_time_milli = System.currentTimeMillis();
long window_position_sec = (long)( ((long)(curr_time_milli/1000))/loop_max_duration); // fraction discarded
long loop_start_time_sec = (window_position_sec + 1 ) * loop_max_duration;
long actual_start_time_milli = loop_start_time_sec * 1000;
Log.i(LOG_TAG, "toastLoop(): starting in " + ((actual_start_time_milli - curr_time_milli)/1000) );
Message msg = handler.obtainMessage( TOAST);
handler.sendMessageAtTime( msg, actual_start_time_milli );
return true;
}
return false;
}
}
public boolean beginTest( View view) {
Log.i(LOG_TAG, "in beginTest()");
test_status = true;
toast_loop = new ToastLoop();
toast_loop.toastLoop();
return true;
}
public boolean endTest( View view) {
Log.i(LOG_TAG, "in endTest()");
test_status = false;
return true;
}
}