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.
Related
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'm trying to create a session with Quickblox, but I'm never getting an answer from Quickblox. onConnect or onError is not firing. I'm testing from an emulator.
My Code:
package com.example.jdc.testjdclogin2;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.model.QBSession;
import com.quickblox.core.QBCallback;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.QBSettings;
import com.quickblox.core.result.Result;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import java.util.List;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
}
public void LoginClicked(View view){
QBUser user = new QBUser();
user.setEmail("testuser#gmail.com");
user.setPassword("Abcd_1234");
QBSettings.getInstance().setApplicationId("19425");
QBSettings.getInstance().setAuthorizationKey("4DuqMR78cuBdMu9");
QBSettings.getInstance().setAuthorizationSecret("Tc8Ukxq-XUBLYz4");
QBAuth.createSession(new QBEntityCallbackImpl<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle params) {
// You have successfully created the session
//
// Now you can use QuickBlox API!
Log.i("Connection","session succeeded");
}
#Override
public void onError(List<String> errors) {
Log.i("Connection","session not succeeded");
}
});
QBUsers.signIn(user, new QBEntityCallbackImpl<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle params) {
Log.i("Connection","login succeeded");
}
#Override
public void onError(List<String> errors) {
Log.i("Connection","login not succeeded");
}
});
Log.i("Connection","End of procedure");
}
}
in the Logcat, I see the call to quickblox but never an answer. Any ideas?
Found the user => forgot to add the permission to use the internet
I want to make a button appear in the MenuActivity layout but the deciding if statement is in the CapitalReceiver class. I've tried adding 'static' to various variables but it didn't work. Please help!
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.DateFormat;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class MenuActivity extends Activity {
String status;
Boolean verified = false;
String textColour = "#000000";
TextView mTvCapital;
ArrayAdapter<String> mAdapter;
Intent mServiceIntent;
CapitalReceiver mReceiver;
IntentFilter mFilter;
String country = "7ec47294ff3d8b74";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_layout);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Button IDButton = (Button) findViewById(R.id.getIt);
Button RefreshButton = (Button) findViewById(R.id.refresh);
long updateTimeMillis = System.currentTimeMillis();
String updateTime = (String) DateFormat.format("hh:mm", updateTimeMillis);
//If application has been submitted//
if(preferences.contains("first_middle_store") & !(verified)) {
status = "Status: Application pending. Last updated: " + updateTime;
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.VISIBLE);
textColour = "#000000";
}
//If application has not been submitted
else {
status = "Status: Application not yet submitted";
IDButton.setVisibility(View.GONE);
RefreshButton.setVisibility(View.GONE);
textColour = "#000000";
}
TextView text=(TextView)findViewById(R.id.application_status);
text.setTextColor(Color.parseColor(textColour));
text.setText(status);
Button btnNextScreen = (Button) findViewById(R.id.verify);
//Listening to verify event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen = new Intent(getApplicationContext(), VerifyActivity.class);
startActivity(nextScreen);
}
});
Button btnNextScreen2 = (Button) findViewById(R.id.how);
//Listening to HowItWorks event
btnNextScreen2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen2 = new Intent(getApplicationContext(), HowItWorksActivity.class);
startActivity(nextScreen2);
}
});
//Listening to IDbutton event
IDButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent nextScreen3 = new Intent(getApplicationContext(), IDActivity.class);
startActivity(nextScreen3);
}
});
}
#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, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_layout, container, false);
return rootView;
}
}
public void refresh(View view) {
// Getting reference to TextView
mTvCapital = (TextView) findViewById(R.id.tv_capital);
mTvCapital.setText("hello");
// Creating an intent service
mServiceIntent = new Intent(getApplicationContext(), CapitalService.class);
mServiceIntent.putExtra(Constants.EXTRA_ANDROID_ID, country);
// Starting the CapitalService to fetch the capital of the country
startService(mServiceIntent);
// Instantiating BroadcastReceiver
mReceiver = new CapitalReceiver();
// Creating an IntentFilter with action
mFilter = new IntentFilter(Constants.BROADCAST_ACTION);
// Registering BroadcastReceiver with this activity for the intent filter
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mReceiver, mFilter);
}
// Defining a BroadcastReceiver
private static class CapitalReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String capital = intent.getStringExtra(Constants.EXTRA_APPROVAL);
if(capital == "YES") {
//status = "Status: Application Approved";//
//IDButton.setVisibility(View.VISIBLE);//
}
else if(capital == "NO"){
//status = "Status: Application Denied";//
}
}
}
}
Just glancing over your code, a possible solution (and perhaps not the best) would be to make the ID Button variable global. You would then instantiate it in the onCreate whilst still allowing it to be manipulated in other classes in this MenuActivity.
I hope this helps.
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();
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;
}
}