I want to start a game from a menu. In Eclipse, I have 2 projects, one with the menu, the other the actual game. Both using SimpleBaseGameActivity as their base. The examples on the net do something like below. In particular, it creates an intent and starts an activity with that intent. The code below gives a NoClassDefFoundError on MyGame.class. This is no surprise since MyGame.class doesn't exist, but rather MyGame.apk does. How do I do this?
public boolean onMenuItemClicked(final MenuScene pMenuScene,
final IMenuItem pMenuItem,
final float pMenuItemLocalX,
final float pMenuItemLocalY) {
switch(pMenuItem.getID()) {
case MENU_PLAY:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(getApplication(), MyGame.class);
startActivity(intent);
finish();
}
});
return true;
}
}
----- edit
I've got it working, with everything in one project, in that when the menu item is clicked on, then the game starts. However, when the 'back arrow' is clicked, it doesn't return to the menu, but rather to the operating system. The activity definitions in the manifest file are below. Does this look correct?
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mygame.MyGame"
android:label="#string/mygame_activity"
android:parentActivityName="com.menu.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.menu.MainActivity" />
</activity>
I added this to MyGame, but it doesn't get called:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
--- edit
I needed to remove this line:
MainActivity.this.finish();
first insert in the Manifest in the tags
<application>...</application>
this tag:
<activity
android:name=".MyGame"
android:label="MygameName" >
</activity>
and change in your code:
public boolean onMenuItemClicked(final MenuScene pMenuScene,
final IMenuItem pMenuItem,
final float pMenuItemLocalX,
final float pMenuItemLocalY) {
switch(pMenuItem.getID()) {
case MENU_PLAY:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(MainActivity.this, MyGame.class);
startActivity(intent);
MainActivity.this.finish();
}
});
return true;
MyGame have to be an activity and it must be mentioned in Android.manifest as an activity.
http://developer.android.com/training/basics/firstapp/starting-activity.html
Please Remove call to function "finish()" and then it will take you back to the parent activity.
Related
I have an app with two activities: MainActivity, which contains a URL entry field where the user can enter a YouTube video URL and press a submit button, to start the second activity, VideoActivity, which displays some information about this video (fetched from another web server).
The app also has a feature to receive intent via the Youtube application. When user presses the share button within the Youtube app, my app appears in the share list. Upon pressing share from the Youtube app, MainActivity should be brought to the front, and the URL should be posted within the MainActivity's URL field.
However, this only happens correctly on the first share. If the app is in the background when user shares from Youtube app, they are taken to whatever the last visible activity was, whether it is MainActivity or VideoActivity, (and even if it is MainActivity, the URL is not posted into the URL field, but the field is left in whatever state it was in when the app was last visible).
Here is my current AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.youcmt.youdmcapp">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".MainActivity"
android:launchMode="singleTop">
<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.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity
android:name=".VideoActivity"
android:parentActivityName=".MainActivity"/>
<service
android:name=".FetchVideoService"
android:exported="false"/>
</application>
</manifest>
Here is my MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private ResponseReceiver mReceiver;
private EditText mUrlEditText;
private Button mSearchButton;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
mUrlEditText = findViewById(R.id.url_search_et);
Intent intent = getIntent();
if (intent.getType()!=null &&
intent.getType().equals("text/plain")) {
Bundle extras = getIntent().getExtras();
String value = extras.getString(Intent.EXTRA_TEXT);
if(value!=null)
{
mUrlEditText.setText(value);
}
}
mProgressBar = findViewById(R.id.progress_bar);
mSearchButton = findViewById(R.id.search_button);
mSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
askForVideo(mUrlEditText.getText().toString());
mSearchButton.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} catch (Exception e) {
mUrlEditText.setText("");
mUrlEditText.setHint(e.getMessage());
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
//register the ResponseReceiver
mReceiver = new ResponseReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(FETCH_VIDEO_INFO);
registerReceiver(mReceiver, intentFilter);
}
private void askForVideo (String url) throws Exception {
try {
Intent intent = FetchVideoService.newIntent(this, url);
startService(intent);
} catch (Exception e) {
mUrlEditText.setText(e.getMessage());
}
}
public class ResponseReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_VIDEO_STATUS, FAIL);
mProgressBar.setVisibility(View.INVISIBLE);
mSearchButton.setVisibility(View.VISIBLE);
if(status==FAIL)
{
mUrlEditText.setText("");
mUrlEditText.setHint("Error retrieving video!");
}
else if(status==SUCCESS) {
Video video = intent.getParcelableExtra(EXTRA_VIDEO);
Intent videoActivityIntent =
VideoActivity.newIntent(getApplicationContext(), video);
startActivity(videoActivityIntent);
}
}
}
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
I do not think any of the other files will be useful in understanding the problem. Although this seems like something many app creators should have to deal with, I can find no answers to this problem. Please comment if you feel I should add any additional information and thank you in advance for any help!
Update: testing demonstrates that after the first use of "Share" from YouTube (and considering app remains in the background), the MainActivity no longer receives any new intent on further shares. However, my app is still brought to the foreground somehow. This is very confusing to me.
When you share from another app, your MainActivity is brought to the front and onNewIntent() is called on it. You don't override onNewIntent() so you never see the share Intent.
I'm using this code on MainActivity for a splashscreen that works perfectly
final ImageView splash1 = (ImageView) this.findViewById(R.id.splash);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
splash1.setVisibility(View.GONE);
}
}, 1000);
but everytime I'm back on MainActivity (where the main menu is), the splashScreen is there again. Is there a way to keep using this code, and just adding an if condition do not see the splashScreen after the first time?
(e.g: a variable that changes when the app loads)
Thanks in advance
Use 2 different activity SplashActivity and MainActivity.
Your "Splash" activity need to be MAIN LAUNCHER Activity. So modify the AndroidManifest file like this...
<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">
</activity>
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And Jump to MainActivity from SplashActivity after few seconds.. Use this code in SplashActivity.
Handler hadler=new Handler();
hadler.postDelayed(new Runnable() {
#Override
public void run () {
finish();
Intent i = new Intent(context, MainActivity.class);
startActivity(i);
}
}, 3000);
here 3000 is used for 3 seconds. The MainActivity auto start after 3 seconds. Hope it helps.
Use separate activity for splash screen after that go for MainActivity, Don't forget to use finish() in splash screen activity.
This link may help you
http://androidexample.com/Splash_screen_-_Android_Example/index.php?view=article_discription&aid=113&aaid=135
Simply create one variable to know whether its displayed or not.
class YourActivity extends Activity {
boolean isDisplayed;
#Override
protected void onStart() {
if (!isDisplayed) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isDisplayed = true;
splash1.setVisibility(View.GONE);
}
}, 1000);
} else {
splash1.setVisibility(View.GONE);
}
}
}
use finish() after starting the SplashScreen Activity
EDIT:
One more approach can be - Create a boolean application level variable (set to false) by extending Applicationclass & then checking it in the runmethod - If false then show the splash & set it to true, so that it will not execute again.
public class DefaultApplication extends Application {
private boolean isSplashDisplayed = false;
public boolean isSplashDisplayed() {
return isSplashDisplayed ;
}
public void setIsSplashDisplayed(boolean isSplashDisplayed) {
this.isSplashDisplayed = isSplashDisplayed;
}
}
Second Approach -
Its better to create a separate activity for Splash, then call MainActivity from SplashActivity & finish SplashActivity
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, 1000);
Also need to make your SplashActivity as launcher
<activity
android:name=".SplashActivity"
android:label="#string/title_activity_splash_screen" >>
<intent-filter>
<action android:name="android.intent.action.MAIN" />>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
< /activity>
I want to open login_activity on first time entering app, and then on the second entering to app open main_activity.
I create something but it wont work. so I wonder what I'm doing wrong?
this is my LoginActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.username);
userPhone = (EditText) findViewById(R.id.userPhone);
loginBtn = (Button) findViewById(R.id.buttonLogin);
dbHandler = new LogsDBHandler(this);
loginBtn.setOnClickListener(this);
setTitle("AMS - biomasa | prijava");
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();
}
}
public void insert() {
User user = new User (
userName.getText().toString(),
userPhone.getText().toString());
dbHandler.addUser(user);
Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
if (v == loginBtn && validateUser()) {
insert();
}
}
In main activity i have only image and two buttons.
And in manifest I add launcher to main and login activity.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
What am I doing wrong here?
Create one start-up activity call it as SplashActivity
public class SplashActivity extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// decide here whether to navigate to Login or Main Activity
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if (pref.getBoolean("activity_executed", false)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
}
In your LoginActivity simply set activity_executed to true
public void insert() {
User user = new User (
userName.getText().toString(),
userPhone.getText().toString());
dbHandler.addUser(user);
Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show();
//set activity_executed inside insert() method.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();
}
change manifest as below-
<activity android:name=".MainActivity"/>
<activity android:name=".LoginActivity" />
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you can change launcher activity as main activity.so that when you open the application it is starting from main activity there you can check whether he is logged in or not.if he is not logged in you must navigate him to login activity or else you just do it as it is.Following is manifest file..
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity"></activity>
You should add another empty activity (with no UI) that loads before anything.
Then use SharedPreferences to store some value. Thus if the user has already opened your app once, the value is stored. And then use a condition to check this value. If its the value you saved skip login_activity and direct to main_activity else direct to login_activity.
Problem about the line
if (pref.getBoolean("activity_executed", false)) {
You can Implement this method to call inside if(appIsLoggedIn)
public boolean appIsLoggedIn(){
return pref.getBoolean("activity_executed", false);
}
I know it has been explained a hundred times, and I've looked at them all and still can't figure it out. I have experience on BlackBerry 10 QT/C++ but am trying to ride the BlackBerry train into Android and that means learning both Java and the Android way of doing things.
I am following (among other guides) this one
in AndroidManifest.xml
<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>
<service android:enabled="true" android:name=".myService" >
</service>
<receiver android:name="android.support.v4.media.session.MediaButtonReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
I think I have things where they need to be? No?
In myService.java
public class myService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private MediaSessionCompat.Callback mediaSessionCompatCallBack = new MediaSessionCompat.Callback()
{
#Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("MEDIAKEY", "Key Event");
return super.onMediaButtonEvent(mediaButtonEvent);
}
};
private MediaSessionCompat mediaSessionCompat;
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d("SERVICE", "onCreate");
mediaSessionCompat = new MediaSessionCompat(this, "MEDIA");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d("SERVICE", "onDestroy");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d("SERVICE_STARTUP", "onStart");
mediaSessionCompat.setCallback(mediaSessionCompatCallBack);
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
mediaSessionCompat.setActive(true);
return START_STICKY;
}
Any help would be great,
Thanks
EDIT:
Ok I've changed the onCreate() to:
context = getApplicationContext();
mediaSessionCompat = new MediaSessionCompat(context, "MEDIA");
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSessionCompat.setCallback(new MediaSessionCompat.Callback() {
#Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d("MEDIA", "event");
return super.onMediaButtonEvent(mediaButtonEvent);
}
});
and onStartCommand() to:
MediaButtonReceiver.handleIntent(mediaSessionCompat, intent);
mediaSessionCompat.setActive(true);
return super.onStartCommand(intent, flags, startId);
But still no Log.d() on pressing any media keys, I watched the video and it helped me understand it but not getting what the problem is, I'm on API 22 (5.1.1) by the way.
There's a few things in the MediaButtonReceiver documentation you are missing firstly:
You need to add the <intent-filter> for android.intent.action.MEDIA_BUTTON to your .myService - without this, MediaButtonReceiver won't know which Service to forward media buttons to
You need to call handleIntent() in your onStartCommand()
After that, your Service will be set up correctly, but you still won't receive media buttons. As explained in the Media Playback the Right Way talk, you need to become the preferred media button receiver by calling mediaSessionCompat.setActive(true).
You'll also want to make sure you are calling
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSessionCompat.setCallback(mediaSessionCompatCallBack);
This ensures that you say you can handle media buttons and registers your Callback instance with the MediaSessionCompat.
Note that MediaSessionCompat will automatically translate media buttons into the appropriate Callback methods (i.e., play will translate to onPlay() being called, etc) so in many cases you don't need to directly override onMediaButtonEvent().
I'm trying to show a message when a user places a call using the standard android dialer.
I have the following code in my Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTestButtonListener();
Log.i(LOG_TAG, "Activity started...");
}
private void setTestButtonListener()
{
Button testButton = (Button)this.findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.i(LOG_TAG, "Clicked on test...");
Toast.makeText(getApplicationContext(), (CharSequence)"You clicked on the test button" ,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+150));
MainActivity.this.sendOrderedBroadcast(intent, null);
MainActivity.this.startActivity(intent);
Log.i(LOG_TAG, "intent broadcasted... I think... ");
}
});
}
Then in the BroadcastReceiver (well a class that derives from it):
public class OnMakingCallReceiver extends BroadcastReceiver
{
private static final String LOG_TAG = OnMakingCallReceiver.class.getSimpleName() + "_LOG";
#Override
public void onReceive(Context context,Intent intent)
{
Log.i(LOG_TAG, " got here!");
}
}
And then in the AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE" />
<receiver android:name=".OnMakingCallReceiver" android:priority="999">
<intent-filter>
<action android:name="android.intent.action.CALL"/>
</intent-filter>
</receiver>
I click the test button and I see this output.
Clicked on test...
intent broadcasted... I think...
And thats all. I expected to see "got here!".
Any ideas why I don't?
Did you define the receiver in your AndroidManifest.xml?
Also, ACTION_CALL_BUTTON is sent when you click on something that goes directly to the dialer. Are you sure you're doing that.
I used this in AndroidManifest.xml and it works. I think the key thing is the intent NEW_OUTGOING_CALL in the intent-filter.
<receiver android:name=".OnMakingCallReceiver" android:exported="true" android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.ACTION_CALL" />
</intent-filter>
</receiver>
Probably ACTION_CALL could be removed. Also this may need to be added to the manifest:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />