I want to show a splash screen when my app loads up, this is my Java code:
ImageView splash = (ImageView) this.findViewById(R.id.splashscreen);
splash.postDelayed(new Runnable(){
splash.setVisibility(View.GONE);
}, 3000);
But I am getting the error "cannot resolve symbol" on the postDelayed() call. Also I get the "unexpected token" for
}, 3000);
Finally, this is my layout:
<TextView
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/splashscreen"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/splash"
android:layout_gravity="center"/>
Logcat:
9:41:01 PM Throwable
Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
Details: Current thread: Thread[ApplicationImpl pooled thread 239,4,main] 359404630
Our dispatch thread:Thread[AWT-EventQueue-0 0.4.2#AI-133.970939, eap:true,6,main] 1198871553
SystemEventQueueThread: Thread[AWT-EventQueue-0 0.4.2#AI-133.970939, eap:true,6,main] 1198871553
9:41:13 PM Compilation completed successfully in 12 sec
The manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.conversation" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.conversation.splash"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
You can do as follows:
private static final int SPLASH_TIME_OUT = 2000;
private static final Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), YourActivity.class));
finish();
}
}, SPLASH_TIME_OUT);
}
Here activity_splash.xml is your splash Activity layout and YourActivity is the Activity you're going to next.
private ImageView splash;
splash = (ImageView)findViewById(R.id.splashscreen);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
splash.setVisibility(View.GONE);
}
}, 3000);
Try this.
Related
How can I start an activity when my app is in background? I mean, when it has not been destroyed? I have tried with IntentService and nothing, I just want to make a StartActivity to launch my MainActivity in the background.
Your service needs to be a foreground service.
Here is how.
First in your Manifest.xml file.
Request for permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
......
<!-- Your Service-->
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.FOREGROUND_SERVICE"/>
Start your service with:
startForegroundService(Intent(this, MyService::class.java))
Then in your service display the foreground notification(usually in the onStartCommand):
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val ncCompat = NotificationChannelCompat.Builder("your.own.id.here", NotificationManagerCompat.IMPORTANCE_DEFAULT).setName("Important").build()
NotificationManagerCompat.from(baseContext).createNotificationChannel(ncCompat)
startForeground("your.notification.id.goes.here".hashCode(), NotificationCompat.Builder(baseContext, nmCompat.id).setContentTitle("My Foreground Service").setContentText("Running Service").build())
return super.onStartCommand(intent, flags, startId)
}
Then your can start an activity(for example: see below)
val intent = Intent(application, MainActivity2::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME)
intent.addFlags(Intent.FLAG_FROM_BACKGROUND)
startActivity(intent)
Android may complain that your activity needs to inherit theme from Theme.AppCompat and you may also have difficulties loading an xml layout.
I believe your can work around those. Apart from that your are good to go.
And also note that i only tested it on Android 10 and below.
Right-click on the project, Select New >> Service >> Service and add the following to MyServices.java
public class MyService extends Service {
public MyService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
onTaskRemoved(intent);
Toast.makeText(getApplicationContext(),"This is a Service running in Background",
Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:text="Click here"
android:textStyle="bold"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Add the following code to src/MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplicationContext(),MyService.class));
}
});
}
}
Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<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">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application.
Click on the Click here button to start background services.
So I have an app that currently has two Activities. A SplashScreenActivity and a MainActivity. The transition between the two activities works just fine but the problem lies in the SplashScreenActivity itself. In it, there is a single ImageView that is supposed to be initially invisible and then fade in. But instead the image remains invisible the entire time. Please help. Here's the code:
The SplashScreenActivity:
package com.degioncloud;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
ImageView logo = (ImageView) findViewById(R.id.iv_logo);
logo.setImageAlpha(0);
logo.animate().alpha(1f).setDuration(1200).withEndAction(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
finish();
}
});
}
}
The XML of the SplashScreenActivity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SplashScreenActivity">
<ImageView
android:id="#+id/iv_logo"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#mipmap/ic_launcher"
android:layout_centerInParent="true" />
</RelativeLayout>
My Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.degioncloud">
<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/Theme.DegionCloud">
<activity android:name=".MainActivity" />
<activity android:name=".SplashScreenActivity"
android:theme="#style/SplashScreenTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The MainActivty is empty so I don't see a need to share that but if you need any other file then let me know and I will send a copy.
You need to call start() for the animation to begin:
logo.animate().alpha(1f).setDuration(1200).withEndAction(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
finish();
}
}).start();
I'm making an Android game in Android Studio.
I first wrote the code for game loop. Then I created a a welcome page/start page and added it to the onclick event.
But when I run the app, and click the "start" button, the app stops abruptly. Here is the Java, XML and manifest files. Did I miss something?
My main activity (Game.java):
public class Game extends ActionBarActivity{
private static Button button_sbm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//turn off title
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game);
onClickButtonListener();
}
public void onClickButtonListener(){
button_sbm=(Button)findViewById(R.id.button);
button_sbm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent("com.project.androidgame.GAME");
startActivity(intent);
}
}
);
}
/*public void startGame(){
Intent intent=new Intent(Splash.this, Game.class);
startActivity(intent);
}*/
activity_game.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START"
android:textSize="50sp"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="How to play"
android:textSize="24sp"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
activity for the starting page (Splash.java):
public class Splash extends Activity {
MediaPlayer ourSong;
#Override
protected void onCreate(Bundle ILoveFootball) {
super.onCreate(ILoveFootball);
setContentView(R.layout.splash);
ourSong=MediaPlayer.create(Splash.this,R.raw.splashsound);
ourSong.start();
Thread timer=new Thread(){
public void run()
{
try{
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint=new Intent("com.project.androidgame.GAME");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
ourSong.release();
finish();
}
}
splash.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_back">
manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:screenOrientation="landscape"
android:name=".Splash" android:label="AndroidGame">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:screenOrientation="landscape"
android:name=".Game" android:label="AndroidGame">
<intent-filter>
<action android:name="com.project.androidgame.GAME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Follow this step to edit your code
In your manifest, remove the intent-filter in the second activity, intent-filter is only use to recognize a start up activity. Change this
<activity android:screenOrientation="landscape"
android:name=".Game" android:label="AndroidGame">
<intent-filter>
<action android:name="com.project.androidgame.GAME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
To this
<activity android:screenOrientation="landscape"
android:name=".Game" android:label="AndroidGame">
</activity>
The best way to start an activity is the present content to the next class an example
Intent intent=new Intent(Splash.this, Game.class);
startActivity(intent);
I am developing an Android app consisting of two activites so far. The first activity (MainActivity) is started when the app is launched or when a QR code is scanned. The MainActivity starts the second activity (NFCActivity) when the user presses a button. The NFCActivity waits for the user to tap a NFC token, reads out data from the token, and returns the read data to the MainActivity.
This works fine if the app is started manually. If the app is started by scanning a QR code, taping the NFC tag does not invoke the NFCActivity's onNewIntent() method as exepcted, but instead creates a new instance of the NFCActivity on top of the already displayed one.
The enableForegroundDispatch() method is called and FLAG_ACTIVITY_SINGLE_TOP should be set. Relevant source code of a minimal example is provided below. Any help would be highly appreciated!
MainActivity:
public class MainActivity extends Activity {
private EditText dataRead;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
dataRead = (EditText) findViewById(R.id.data);
final Button readKeyButton = (Button) findViewById(R.id.readNFC);
readKeyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent keyIntent = new Intent(MainActivity.this,
NFCActivity.class);
keyIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(keyIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 1) {
String result = intent.getExtras().getString("resultData");
this.dataRead.setText(result);
}
}
}
Main Activity's GUI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/readNFC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="127dp"
android:text="Read NFC Tag" />
<EditText
android:id="#+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/readNFC"
android:layout_centerHorizontal="true"
android:layout_marginBottom="85dp"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
NFCActivity:
public class NFCActivity extends Activity {
private NfcAdapter mAdapter;
private PendingIntent pendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_nfc);
mAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// // Setup an intent filter for all MIME based dispatches
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
mFilters = new IntentFilter[] { ndef, td };
//
// // Setup a tech list for all NfcF tags
mTechLists = new String[][] { new String[] { NfcV.class.getName(),
NfcF.class.getName(), NfcA.class.getName(),
NfcB.class.getName() } };
}
#Override
public void onResume() {
super.onResume();
if (mAdapter != null)
mAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
mTechLists);
}
#Override
public void onPause() {
super.onPause();
if (mAdapter != null)
mAdapter.disableForegroundDispatch(this);
}
#Override
public void onNewIntent(Intent intent) {
Log.d("TEST", "onNewIntent() called.");
// READ THE NFC TAG HERE [SKIPPED FOR MINIMAL EXAMPLE]
// Return dummy data for test
Intent result = new Intent();
result.putExtra("resultData", "DUMMY DATA");
setResult(1, result);
finish();
}
}
NFCActivity's GUI:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#303030"
android:paddingLeft="30dp"
android:paddingRight="30dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Tap your NFC tag.."
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF8811"
android:textSize="30sp"
android:textStyle="bold" />
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.nfcqrtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="test.nfcqrtest.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="test.org" android:pathPrefix="/testapp" />
</intent-filter>
</activity>
<activity
android:name=".NFCActivity"
android:windowSoftInputMode="stateHidden" android:screenOrientation="portrait" android:launchMode="singleTop">
</activity>
</application>
</manifest>
In case somebody is facing a similar problem: I was finally able to overcome the issue described above by setting the android:launchMode property for the MainActivity to singleInstance.
this is my codes LoginActivity.java file
package com.example.crims;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
public class LoginActivity extends Activity {
TextView screen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
screen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
screen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
}
}
this is my code for 'activity_login.xml' file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".LoginActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>`
And Finally this is my menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.crims"
android:versionCode="1"
android:versionName="1.0" >
<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.crims.LoginActivity"
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=".RegisterActivity"
android:label="Register New Account">
</activity>
</application>
</manifest>
All of these files are here and i want to find my error as I m new to android app development...
You have NullPointerException(NPE) here:
10-01 21:02:07.580: E/AndroidRuntime(1299):
at com.example.crims.LoginActivity.onCreate(LoginActivity.java:17)
So, check line 17 of LoginActivity.java (you can just double click on this message in the logcat view and you will be navigated to this line).
It seems, line 17 is this:
registerScreen.setOnClickListener(new View.OnClickListener() {
As this is NPE, registerScreen is null. So, you should inspect why it is null. This is because Activity can't find it in line above and it returns null instead:
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
This can be one of two possibilities: either you do not have widget with id 'link_to_register' in activity_login.xml, or something other is wrong :)
Check this please and show your activity_login.xml file, please.
Listen brother take this code. Change it according to you.
public class MainActivity extends Activity {
TextView screen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.screen);
// Listening to register new account link
screen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), Register.class);
startActivity(i);
}
});
}
}
You need to register your activity in manifest.xml file too in case if you don't know about it.