Android activity starting twice on startup - java

SplashActivity .java
public class SplashActivity extends Activity {
private static String TAG = SplashActivity.class.getName();
private static long SLEEP_TIME = 4; // Time to display the splash image for
// in seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes
setContentView(R.layout.activity_splash);
Log.d("man", "Starting app");
testHttp test = new testHttp();
test.test();
}
Here is the Manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.rhino68mobileapp.SplashActivity"
android:label="#string/title_activity_splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
When I run my app on my device this is what the logs read:
03-06 06:12:16.819: D/man(2105): Starting app
03-06 06:12:16.819: D/TEST(2105): Starting test
03-06 06:12:16.869: D/TEST(2105): make request
03-06 06:12:16.869: D/man(2105): Starting app
03-06 06:12:16.869: D/TEST(2105): Starting test
03-06 06:12:16.869: D/TEST(2105): make request

Try this for your splash screen:
public class Splash extends Activity implements Runnable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(this, 1500); // SLEEP_TIME in milis
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
public void run(){
startActivity(new Intent(this, Main.class)); // Call the after splash screen
finish();
}
}

Related

Android keep app running in the background forever

I am still new to Android development, but I’m creating an app that sendings an HTTP request when it receives a broadcast (from a barcode scan). I have tried to implement some other solutions that I read on here but haven't quite figured it out yet. It would be great if someone could help me get going in the right direction.
Essentially, the end goal is for the app to keep running in the background forever so that even if the app is not open and a barcode is scanned and sent to the app via broadcast signal, the HTTP request is still sent.
This is what I have so far:
MainActivity.java
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
public static final String BARCODE_BROADCAST = "...";
private final BarcodeReceiver barcodeReceiver = new BarcodeReceiver();
private TextView mTextView;
private String scannedBarcode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.barcode);
}
#Override
public void onResume() {
super.onResume();
registerBarcodeScanner();
}
#Override
public void onPause() {
super.onPause();
unregisterBarcodeScanner();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
public void onDestroy() {
super.onDestroy();
// this code needs to keep the app running
Intent restartService = new Intent("RestartService");
this.startService(restartService);
sendBroadcast(restartService);
}
private void registerBarcodeScanner() {
registerReceiver(barcodeReceiver, new IntentFilter(BARCODE_BROADCAST));
}
private void unregisterBarcodeScanner() {
unregisterReceiver(barcodeReceiver);
}
private void displayBarcode() {
if (scannedBarcode == null) return;
String text = getString(R.string.barcode_scanned, scannedBarcode);
mTextView.setText(text);
/* SEND HTTP REQUEST */
}
private class BarcodeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BARCODE_BROADCAST)) {
String barcode = intent.getStringExtra("Barcode");
if (barcode != null) {
scannedBarcode = barcode;
displayBarcode();
}
}
}
}
}
RestartService.java
public class RestartService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MainActivity.class));
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="..."
android:versionCode="1">
<uses-sdk android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
tools:replace="android:label">
<activity
android:name="...MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="...RestartService"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="RestartService" />
</intent-filter>
</receiver>
</application>
</manifest>

Android app opens after a few seconds after pressing home button during splash screen

I am having an issue I can't seem to figure out the reason for.
When you launch the app, a splash screen is first displayed for 2.5 seconds before finishing and starting a new activity. If you press the home or back button during this time the app will close as normal. However after a few seconds (longer than 2.5) the app will open and start from the activity that comes after the splash screen.
Any help on why this happens is appreciated!
Here is the implementation of the Splash screen (I do however not believe anything here causes this issue as I've tried different implementations)
`public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2500);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();`
Here's the manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode = "singleInstance">
</activity>
<activity android:name=".activities.SplashScreenActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".alert.BroadCaster" >
</receiver>
<service android:name=".timer.TimerService"
android:process=":timerservice" />
</application>
It happens because you are creating a new Thread and this thread will be still alive after you put your app in background. You can change your approach using an Handler. If you need that your next Activity won't start if the splash screen is in background, you have to store the current time before the delay starts.
private static final long SPLASH_SCREEN_MS = 2500;
private long mTimeBeforeDelay;
private Handler mSplashHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// Create a new Handler.
mSplashHandler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
// The first time mTimeBeforeDelay will be 0.
long gapTime = System.currentTimeMillis() - mTimeBeforeDelay;
if (gapTime > SPLASH_SCREEN_MS) {
gapTime = SPLASH_SCREEN_MS;
}
mSplashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, gapTime);
// Save the time before the delay.
mTimeBeforeDelay = System.currentTimeMillis();
}
#Override
protected void onPause() {
super.onPause();
mSplashHandler.removeCallbacksAndMessages(null);
}
Just use handler instead of thread sleep like this
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, SPLASH_DURATION);
You need to implement the onStop() method, only if you want to save data and memory.

android Broadcast Receiver not works

I programming with android studio and I want to have a Broadcast receiver to do something every time the time of clock change (it means every single minute that for example the time of phone changed from 3:13 to 3:14) even if the program isn't run. so I should use a Broadcast receiver with Time_Tick Action. But It just work when the Activity created. any Idea?
MainActivity:
public class MainActivity extends ActionBarActivity {
BroadcastReceiver br;
final SmsManager sms = SmsManager.getDefault();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter i=new IntentFilter();
i.addAction("android.intent.action.TIME_TICK");
registerReceiver(new MyReceiver(),i);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#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);
}
}
MyReceiver:
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
Log.i("Saaalam","saaaalaalam");
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.etsiamak.broadcastrecierver" >
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="ANDROID.PERMISSION.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter> <action android:name="android.intent.action.TIME_TICK"></action> </intent-filter>
</receiver>
</application>
</manifest>
Here is the sample code for time tick. The TIME_TICK intent gets fired minute change.
static TimeReceiver tickReceiver = new TimeReceiver();
void setTimeTick()
{
registerReceiver(tickReceiver, new IntentFilter(
"android.intent.action.TIME_TICK"));
Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
.show();
//Register the broadcast receiver to receive TIME_TICK
registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
The Reciever Class
class TimeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(context, "Time tick", Toast.LENGTH_LONG).show();
}
}
Can you add this code into Manifest
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
What I understand is that you need to execute certain task after certain amount of time say one minutes. For this you can use AlarmManager.
AlarmManager myAlarmManager = Context.getSystemService(Context.ALARM_SERVICE)
Example for AlarmManager: https://androidresearch.wordpress.com/2012/07/02/scheduling-an-application-to-start-later/
Or Android introduced the JobScheduler API in Android 5.0 (API 21). It is better then AlarmManager as it does not consider if the device is connected to a power plug, idle or connected.
Example for JobScheduler: how-to-use-androids-job-scheduler

Why wont my splash screen work?

I'm pretty new to Java and xml i'm looking to have a splash screen run when i start up my app for about 5 seconds. I've taken code for the splash screen from stack overflow to set it up but i cant get it to run for some reason could anybody help me out!
Cheers
MY splash class
package com.darraghoflaherty.competer.game;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
public class Splash extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 5000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,Menu.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
My xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0099FF">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/ss1"
android:id="#+id/ss1"
android:textColor="#ffffff"
android:textSize="260sp"/>
</RelativeLayout>
first change this peace of code :
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,Menu.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
To
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(getApplicationContext(),Menu.class);
startActivity(mainIntent);
finish();
}
Now your code is clear, the error must come from the manifest file.
Go to the manifest file and change the position of the intent-filter from the Mainactivity to the slashscreen activity.
here the code :
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
My guess is that you have not changed the launcher activity in the manifest. Android looks in the AndroidManifest.xml to select the activity to start first. Your manifest probably contains these lines:
<activity android:name=".Menu" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This should be changed to:
<activity android:name=".Splash" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Menu"/>
It is also a good convention to name activities XyzActivity, so in your case MenuActivity and SplashActivity.
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
Thread timer = new Thread(){
public void run(){
try{
Thread.sleep(2000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent mainIntent = new Intent(Splash.this,Menu.class);
startActivity(mainIntent );
finish();
}
}
};// end thread
timer.start();
use this code for the splash screen ...
public class SPLASH extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000; // time to display the splash screen in MICROSECONDS
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while (_active && (waited < _splashTime)) {
sleep(100);
if (_active) {
waited += 100;
}
}
} catch (Exception e) {
} finally {
startActivity(new Intent(Splash.this,Menu.class));
finish();
}
};
};
splashTread.start();
}
}
and make the Splash activity a launcher activity by using
<activity
android:name=".SPLASH"
android:label="#string/app_name"
android:theme="#style/NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Hope this will help u
Hey checkOut it i have improve little bit. thanks
public class Splash extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 5000;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
nav();
}
public void nav() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(Splash.this,Menu.class);
startActivity(mainIntent);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}

Android not starting other activity

I'm pretty new to Android programming, but i have never encountered this problem before. When i click the button, the emulator is just not doing anything, when it's supposed to start another activity. Here's my intent within the button:
public class StartScreen extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bStartQuiz:
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
break;
Here follows some more cases which are not defined yet.
onCreate method from the class i try to start:
public class QuizMenu extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
Here is the manifest:
<activity
android:name="com.ultimatequiz.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.ultimatequiz.QuizMenu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.ultimatequiz.QuizMenu" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
What i really don't understand is that i get no errors in the log. It's just not "responding", but the button do change into state_pressed.
If I understood correctly you want to open a new activity by clicking a Button. Then all you have to do is to have a Button in your activity_start_screen.xml:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/your_button"/>
After that you have to add this in your StartScreen:
public class StartScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent activityChangeIntent = new Intent(StartScreen.this,QuizMenu.class);
StartScreen.this.startActivity(activityChangeIntent);
}
});
and only this in your manifest:
<activity
android:name="com.ultimatequiz.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.ultimatequiz.QuizMenu"
android:label="#string/app_name"/>
I dont know if your case works well.Try this.
public class StartScreen extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
Button myBtn = (Button) findViewById(R.id.btn);
myBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
}
});
}
}
I always use this way, I find it easy to handle.
if you got your layout defined onlick delete it
Try to do a function for it :
public static void LaunchIntent(){
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
and in the click listener call the function :
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bStartQuiz:
LaunchIntent();
break;
}

Categories