Button displays toast and starts service - java

I have two buttons (start/stop) that when clicked need to have a Toast pop up saying what has happened to the Service. Start = popup of "service has started" and the service actually starts. The service isn't finished and will be grabbing some GPS info later on.
Anyway, none of my Toasts show up and I'm hoping I'm not missing something obvious.
Main (Activity)
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = (Button) findViewById(R.id.startButton);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), ParseService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.startButton);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), ParseService.class));
}
});
}
}
ParseService
public class ParseService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent e, int flags, int startId){
Toast.makeText(this, "Service has Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Service has Stopped", Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<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:textAlignment="center"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="#+id/startButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="92dp"
android:text="Start" />
<Button
android:id="#+id/stopButton"
android:layout_width="150dp"
android:layout_height="60dp"
android:layout_alignLeft="#+id/startButton"
android:layout_below="#+id/startButton"
android:layout_marginTop="74dp"
android:text="Stop" />
</RelativeLayout>

You are supposed to use the Application's Context from a Service and not the Service's Context.
From your Service:
Toast.makeText(getApplicationContext(), // application Context not 'this'
"Service has Started",
Toast.LENGTH_LONG).show();
Alternatively, you could display them from your Activity before you invoke the Service if you wish but I think where you have the calls currently positioned makes more sense and would reduce repetition later on as long as you always want the Toast displayed.
EDIT:
Ok, after making a quick test app I think I found what might be going wrong for you.
Do you have the Service declared in your AndroidManifest.xml??
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.indivisible.testapp">
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".toasts.ToastActivity"
android:label="#string/title_activity_toast">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Define your Service as below.
In my case the path is:
.../TestApp/app/src/main/java/com/indivisible/testapp/toasts/ToastService.java
Android Studio has a nice auto-complete when you press '.'
-->
<service
android:name=".toasts.ToastService"
android:label="ToastService">
</service>
</application>
</manifest>

It seems like your service is not getting started, make sure the service is declared in the manifest and enabled as below:
<service
android:name=".ParseService"
android:enabled="true" />
Hope this helps

Related

¿How can i launch my app or an activity in background?

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.

Pressing a button is supposed to start service and display text, but nothing happens when I click the button

I'm new to Java and I was trying to make a simple program to display text when a button is pressed by using services. For some reason nothing happens when I press the "Start Service" and "Stop Service" buttons. Here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
public static class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
And the buttons-
<Button
android:id="#+id/button"
android:layout_width="132dp"
android:layout_height="105dp"
android:layout_marginTop="8dp"
android:onClick="startService"
android:text="#string/Buttton1"
android:visibility="visible"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="128dp"
android:layout_height="108dp"
android:layout_marginTop="8dp"
android:onClick="stopService"
android:text="#string/Button2"
android:visibility="visible"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
A few things wrong.
1: I don't think your service should be static.
2: Did you declare your service in your AndroidManifes.xml?
3: You don't need to use getBaseContext()
If you're in an activity use this
If you're in a fragment use getActivity()
So you have to declare all your services same as all your activities in the android manifest.To do that navigate to your apps manifest located under app>manifest>AndroidManifext.xml.Next, you need to add a service tag under application with the name of your service.
Example code:
<?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="com.example.android.myapplication">
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<service android:name=".MyService"/> <-----This is were you declared your service
<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>
</application>
</manifest>
Everything should work fine after that.
I was using a fragment that's why it wasn't working. I used MainActivity and it worked. Thanks for the answers!

resume button not working to go last activity

have 4 activity : Main Activity,p1,p2,p3
my resume button not working . i want when i click in resume button app open my last activity .
for example : when in p2 click go to main , then in main when click resume , p2 open . here is my code :
Main Activity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
Button resume = (Button) findViewById(R.id.resume);
Button next = (Button) findViewById(R.id.next);
Button exit = (Button) findViewById(R.id.exit);
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPref = getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
String lastActivity= myPref.getString("lastactivity","");
try {
Intent fooActivity = new Intent(MainActivity.this,Class.forName(lastActivity));
startActivity(fooActivity);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, p1.class);
startActivity(intent);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
}
}
XML layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="resume"
android:layout_width="wrap_content"
android:id="#+id/resume"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit"/>
</LinearLayout>
p1 :
public class p1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button next = (Button) findViewById(R.id.next);
Button home=(Button)findViewById(R.id.home);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, p2.class);
startActivity(intent);
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(p1.this, MainActivity.class);
startActivity(intent);
}
});
}
private void storeCurrentActivity(){
SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPref.edit();
editor.putString("lastactivity", this.getClass().getSimpleName());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
storeCurrentActivity();
}
}
XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="page 1"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home"/>
</LinearLayout>
and p2,p3 like p1
and this my manifast :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.er.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".p1"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p2"
android:label="#string/title_activity_p2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".p3"
android:label="#string/title_activity_p3"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
</manifest>
you have to do below things to achieve what you want
whenever you open activity you have to save previous activity name in prefrance.
when you press resume button get activity name from prefrance and open activity using below code
Intent intent = new Intent();
intent.setClassName("com.android.browser","com.android.BrowserActivity");
context.startActivity(intent);
// clear previous activity before start
when you app relaunch app then do step 2 again in main Activity
in this type of approch you have to maintain flow of application using singletone or clear stack before launch activity. because you have to handle backbutton

Using QR and NFC technology together in an Android app

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.

Android App won't display in Android Studio Emulator

I am very new to Android development. I have tried to recreate an app where if you press a button, a message "new text string" is displayed. However, when I run the AVD and choose the Virtual Device, it doesn't display it. Just an old TestApp I had. Can anyone suggest a fix? I'd really appreciate it.
My code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/hello_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:id="#+id/trigger"
android:layout_width="100dip" android:layout_height="100dip"
android:text="#string/button1"
android:layout_below="#+id/hello_text"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="111dp" />
</RelativeLayout>
SimpleActivity.java
package com.example.simpleactivityexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.*;
import android.view.View;
public class SimpleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener()
{
private TextView tv = (TextView) findViewById(R.id.hello_text);
public void onClick(View view)
{
tv.setText("new text string");
}
}
);
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
super.onPause();
}
#Override
protected void onStop() {
Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onDestroy() {
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simpleactivityexample" >
<application
android:debuggable="true"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.simpleactivityexample.SimpleActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Dietary Application</string>
<string name="hello">Hello!</string>
<string name="button1">This is a button!</string>
</resources>
I managed to solve it.I am using Android Studio by the way.
I went to the run tab at the top of the screen and went into ''Edit Configurations''. I then ticked ''Show chooser dialog''. I started the AVD and when it was fully started, A pressed the run function(green triangle) and it started on the Android. Thanks so much to everyone who helped!
Your code seems fine; check the logcat and console outputs when you click 'Run as Android Application' to see if the install is working.
Logcat is located in the top menu under
Window- Show View - Other - Android - Logcat
Also try cleaning the project and restarting the emulator; and also, if the app doesn't show up when the emulator loads, try, without exiting the emulator, to run it again.
Are you using the latest studio? Seems like an old bug
Error when running emulator in Android Studio
Try waiting until the emulator boots, and then run the project.

Categories