Android: onTouchEvent start new activity - java

I have been searching for a while now but can't find a working solution for my android code. Well at least one I am able to implement.
I have an activity (StartActivity) with a few animations. Then I have an onTouchEvent. This works fine to prompt a few more animations however after this I want to open a new Activity.
Here is my code:
public class StartActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
RunAnimations(R.anim.translate1, R.anim.translate2);
}
public void RunAnimations(int t1, int t2) {
Animation a = AnimationUtils.loadAnimation(this, t1);
a.reset();
Animation b = AnimationUtils.loadAnimation(this, t2);
b.reset();
ImageView drop = (ImageView) findViewById(R.id.drop);
ImageView iflush = (ImageView) findViewById(R.id.iflush);
drop.clearAnimation();
iflush.clearAnimation();
drop.startAnimation(a);
iflush.startAnimation(b);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
RunAnimations(R.anim.translate3, R.anim.translate4);
}
return true;
}
}
In the onTouchEvent, after calling RunAnimations, I want to start a new activity (TipActivity). That is all.

Add another activity to you AndroidManifest file like so:
<activity
android:label="YourActivity"
android:name=".YourActivity" >
<intent-filter >
<action android:name="net.learn2develop.YourActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And then you could do something like (after calling RunAnimations()) :
startActivity(new Intent("net.learn2develop.YourActivity"));
Hope that helps.

Use that:
Intent intent=new Intent(context, TipActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.translate3, R.anim.translate4);
^-^

Related

Android SearchView.OnQueryTextListener() Unexpectedly Launching an Intent

I have implemented a Searchview into my application, and have run into a weird problem. Basically, the user is able to enter a string to be searched and it is submitted properly. However, my application will filter the ListView based on the search query, and then an Intent will be launched resulting in the activity starting again and returning to it's original state where it is displaying all the results.
Here is the related code.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
updateEntriesView(dbHelper.queryByName(query));
Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
private void updateEntriesView(ArrayList<Entry> response) {
mListView = (ListView) findViewById(R.id.listview_entries);
if (adapter == null) {
adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(response);
adapter.notifyDataSetChanged();
}
adapter.setNotifyOnChange(true);
}
I can not figure out to change this behavior and I can not find any documentation regarding it's implementation online. Is there a way I can override this feature and prevent it from launching an intent and restarting the activity to it's original unfiltered state?
EDIT:
I was able to solve this issue myself. For anyone who may be having the same problem here was my solution.
So I had an intent-filter in my AndroidManifest.xml under the activity that would launch an intent upon a search action. This is what was causing it to launch an intent and start a new instance of my activity.
My solution to this was to convert this activity into a single top activity and add code to handle the intent. By making the activity single top, it allows the activity to handle incoming intents without starting up a new instance of the intent. For a more detailed description on the difference between a normal and single top activity, this is a good article on the subject https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/
Now, because my activity is single top, I can override the onNewIntent() method and add my code for handling this intent without having it launch a new instance. The relevant code for solving my problem is below.
AndroidManifest.xml
<activity android:name=".EntriesActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"></meta-data>
</activity>
EntriesActivity.java
public class EntriesActivity extends AppCompatActivity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
updateEntriesView(dbHelper.queryByName(query));
Toast.makeText(getApplicationContext(), "Searching for " + query, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
updateEntriesView(dbHelper.queryEntriesByName(query));
}
}
private void updateEntriesView(ArrayList<Entry> response) {
if (adapter == null) {
adapter = new EntryListAdapter(EntriesActivity.this, R.layout.row_entry_layout, response);
mEntriesList.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(response);
adapter.notifyDataSetChanged();
}
adapter.setNotifyOnChange(true);
}
}
I hope this helps.
You need to clear focus of the text view using searchView.clearFocus();
Refer This Answer: https://stackoverflow.com/a/15127252/7710739
I know this is old but if your searching and resulting in the same Activity try removing the
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
It should not try to launch a new activity then i don't beleive.

Cordova Plugin Stop/Restart Activity

I have a Cordova plugin which uses the https://github.com/googlesamples/android-Camera2Video example. I would like to disable the back button while in Camera.
To do this, I believe Fragments can't accept back button events, so have added an Activity to the plugin. I can successfully run the plugin, camera and activity, disabled the back button.
However when I close the plugin it errors with:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
To get around this I have used commitAllowingStateLoss instead of commit however when I open the plugin the second time, it errors with:
java.lang.NullPointerException: Attempt to invoke interface method 'android.app.Activity org.apache.cordova.CordovaInterface.getActivity()' on a null object reference
I presume I'm not stopping the activity correctly, and allowing the state to be lost, which causes a second error. How do I get around this?
I've tried this method but no luck:
PhoneGap Android Plugin - close the plugin Activity
I've put my code in a branch here:
https://github.com/kmturley/cordova-plugin-media-custom/tree/feature/back-button
Add a summary of the changes:
plugin.xml
<config-file target="AndroidManifest.xml" parent="/manifest/application">
<activity android:name="com.example.android.camera2video.MediaCustomActivity" android:label="#string/activity_name" android:theme="#style/Theme.Transparent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</config-file>
<source-file src="src/android/MediaCustom.java" target-dir="src/com/example/android/camera2video" />
<source-file src="src/android/MediaCustomActivity.java" target-dir="src/com/example/android/camera2video" />
<source-file src="src/android/Camera2VideoFragment.java" target-dir="src/com/example/android/camera2video" />
MediaCustom.java
public void show() {
if (cameraFragment != null) {
return;
}
cameraFragment = Camera2VideoFragment.newInstance(cordova, callbackContext);
cordova.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
cordova.getActivity().setContentView(resources.getIdentifier("activity_camera", "layout", packageName));
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(resources.getIdentifier("container", "id", packageName), cameraFragment);
fragmentTransaction.commit();
MediaCustomActivity.start(cordova.getActivity());
}
});
}
public void hide() {
if (cameraFragment == null) {
return;
}
cordova.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
MediaCustomActivity.stop(cordova.getActivity());
cordova.getActivity().setContentView(getView());
FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(cameraFragment);
fragmentTransaction.commitAllowingStateLoss(); // commit();
cameraFragment = null;
}
});
}
MediaCustomActivity.java
public static void start(Activity activity) {
Intent intent = new Intent(activity, MediaCustomActivity.class);
activity.startActivity(intent);
}
public static void stop(Activity activity) {
// what can we do here?
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
Window window = this.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}

One code and deferent result in android2.2 vs android4.2

In a big project i have below codes that run step is
first GalleryMeno runs and then GalleryActivityMain
GalleryMeno.java
public class GalleryMeno extends Activity{
private Integer[] mThumbIds = {
R.drawable.gallary_farhad1 ,
R.drawable.gallary_farhad2,
R.drawable.gallary_naser ,
R.drawable.gallary_mehdi ,
R.drawable.gallary_other ,
R.drawable.gallary_old ,
R.drawable.gallary_amir ,
R.drawable.gallary_bazikonan
};
private String[] name = {
"gallary_farhad1",
"gallary_farhad2",
"gallary_naser",
"gallary_mehdi",
"gallary_other",
"gallary_old",
"gallary_amir",
"gallary_bazikonan"
};
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_meno_activity);
TextView titleName = (TextView) findViewById(R.id.title_name);
titleName.setText("گالری تصاویر");
//found width of Screen for Gridview
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
int densityX = display.getWidth();
Button btnUpdate = (Button) findViewById(R.id.update);
btnUpdate.setVisibility(View.INVISIBLE);
Button backButton = (Button) findViewById(R.id.backward);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-g
finish();
}
});
GridView grid = (GridView) findViewById(R.id.gridViewSms);
grid.setAdapter(new ImageAdapter(getApplicationContext(), densityX, mThumbIds));
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position ,
long id) {
Intent MainGallery = new Intent(GalleryMeno.this , GalleryActivityMain.class);
MainGallery.putExtra("position", position);
MainGallery.putExtra("title", name[position]);
startActivity(MainGallery);
}
});
}
}
ImageAdapter .java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int widthOfScrren;
public Integer[] mThumbIds;
public ImageAdapter(Context c,int ScrrenSize,Integer[] mThumbIds){
mContext = c;
widthOfScrren=ScrrenSize;
this.mThumbIds = mThumbIds;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
final int w;
if ( widthOfScrren == 0 )
w = 75;
else
w = widthOfScrren/3;
imageView.setLayoutParams(new GridView.LayoutParams(w,w));
return imageView;
}
}
GalleryActivityMain.java
public class GalleryActivityMain extends Activity {
public static Integer[] ImageGroup1 = {
R.drawable.farhad01,
R.drawable.farhad02,
R.drawable.farhad03,
R.drawable.farhad04,
R.drawable.farhad05,
R.drawable.farhad06,
R.drawable.farhad07,
R.drawable.farhad08,
R.drawable.farhad09,
R.drawable.farhad10,
R.drawable.farhad11,
R.drawable.farhad12,
R.drawable.farhad13,
R.drawable.farhad14,
R.drawable.farhad15,
R.drawable.farhad16
};
public static Integer[] ImageGroup2 = {
R.drawable.farhad17,
R.drawable.farhad18,
R.drawable.farhad19,
R.drawable.farhad20,
R.drawable.farhad21,
R.drawable.farhad22,
R.drawable.farhad23,
R.drawable.farhad24,
R.drawable.farhad25,
R.drawable.farhad26,
R.drawable.farhad27,
R.drawable.farhad28,
R.drawable.farhad29,
R.drawable.farhad30,
R.drawable.farhad31,
R.drawable.farhad32,
R.drawable.farhad33
};
public static Integer[] ImageGroup3 = {
R.drawable.naser01,
R.drawable.naser02,
R.drawable.naser03,
R.drawable.naser04,
R.drawable.naser05,
R.drawable.naser06,
R.drawable.naser07,
R.drawable.naser08,
R.drawable.naser09,
R.drawable.naser10,
R.drawable.naser11,
R.drawable.naser12,
R.drawable.naser13,
R.drawable.naser14,
R.drawable.naser15,
R.drawable.naser16,
R.drawable.naser17
};
public static Integer[] ImageGroup4 = {
R.drawable.mehdi01,
R.drawable.mehdi02,
R.drawable.mehdi03,
R.drawable.mehdi04,
R.drawable.mehdi05,
R.drawable.mehdi06,
R.drawable.mehdi07,
R.drawable.mehdi08,
R.drawable.mehdi09,
R.drawable.mehdi10,
R.drawable.mehdi11,
R.drawable.mehdi12,
R.drawable.mehdi13,
R.drawable.mehdi14,
R.drawable.mehdi15,
R.drawable.mehdi16,
R.drawable.mehdi17
};
public static Integer[] ImageGroup5 = {
R.drawable.other01,
R.drawable.other02,
R.drawable.other03,
R.drawable.other04,
R.drawable.other05,
R.drawable.other06,
R.drawable.other07,
R.drawable.other08,
R.drawable.other09,
R.drawable.other10,
R.drawable.other11,
R.drawable.other12,
R.drawable.other13,
R.drawable.other14,
R.drawable.other15,
R.drawable.other16,
};
public static Integer[] ImageGroup6 = {
R.drawable.old01,
R.drawable.old02,
R.drawable.old03,
R.drawable.old04,
R.drawable.old05,
R.drawable.old06,
R.drawable.old07,
R.drawable.old08,
R.drawable.old09,
R.drawable.old10,
R.drawable.old11,
R.drawable.old12,
R.drawable.old13,
R.drawable.old14,
R.drawable.old15,
R.drawable.old16,
R.drawable.old17,
R.drawable.old18,
R.drawable.old19
};
public static Integer[] ImageGroup7 = {
R.drawable.amir01,
R.drawable.amir02,
R.drawable.amir03,
R.drawable.amir04,
R.drawable.amir05,
R.drawable.amir06,
R.drawable.amir07,
R.drawable.amir08,
R.drawable.amir09,
R.drawable.amir10,
R.drawable.amir11,
R.drawable.amir12,
R.drawable.amir13,
R.drawable.amir14,
R.drawable.amir15
};
public static Integer[] ImageGroup8 = {
R.drawable.b1,
R.drawable.b2,
R.drawable.b3,
R.drawable.b4,
R.drawable.b5,
R.drawable.b6,
R.drawable.b7,
R.drawable.b8,
R.drawable.b9,
R.drawable.b10,
R.drawable.b11,
R.drawable.b12,
R.drawable.b13,
R.drawable.b14,
R.drawable.b15,
R.drawable.b16,
R.drawable.b17,
R.drawable.b18,
R.drawable.b19,
R.drawable.b20
};
public static Integer[] SelectedGroup;
private int Global_position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galery_activity);
TextView titleName = (TextView) findViewById(R.id.title_name);
Intent current = getIntent();
Global_position=current.getExtras().getInt("position");
titleName.setText(current.getExtras().getString("title"));
Button btnUpdate = (Button) findViewById(R.id.update);
btnUpdate.setVisibility(View.INVISIBLE);
Button backButton = (Button) findViewById(R.id.backward);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
GridView grid=(GridView) findViewById(R.id.grid_view_gallery);
//connect xml_gridView to Class ImageAdapter
//when we sent 0 to screensize we want to auto generating image independent device
grid.setAdapter(new ImageAdapter(getApplicationContext(), 0, getCorrectItem(Global_position)));
//set item on click listener
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
Intent FullImage = new Intent(getApplicationContext(), GalleryFullImageView.class);
/******
* by below syntax we sent some information by a id
* to new intent and on new intent we extract it and use it
******/
FullImage.putExtra("position", position);
startActivity(FullImage);
}
});
}
private Integer[] getCorrectItem(int position)
{
switch (position) {
case 0:
SelectedGroup = ImageGroup1;
return ImageGroup1;
case 1:
SelectedGroup = ImageGroup2;
return ImageGroup2;
case 2:
SelectedGroup = ImageGroup3;
return ImageGroup3;
case 3:
SelectedGroup = ImageGroup4;
return ImageGroup4;
case 4:
SelectedGroup = ImageGroup5;
return ImageGroup5;
case 5:
SelectedGroup = ImageGroup6;
return ImageGroup6;
case 6:
SelectedGroup = ImageGroup7;
return ImageGroup7;
case 7:
SelectedGroup = ImageGroup8;
return ImageGroup8;
default:
SelectedGroup = ImageGroup7;
return ImageGroup7;
}
}
}
Mymanifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.esteghlaliha"
android:versionCode="8"
android:installLocation="preferExternal"
android:versionName="1.9" >
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/esteghlal_big"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.perspolisiha.Esteghlal"
android:theme="#android:style/Theme.NoTitleBar"
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.example.perspolisiha.Main"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar">
</activity>
<activity android:name="com.example.rank.Resultshow"
android:configChanges="orientation|screenSize"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.rank.RankLayout"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.SmsshowActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryActivityMain"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryFullImageView"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.perspolisiha.GalleryMeno"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.tv.TVLayout"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.tv.TVResultshow"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.bio.BioMainActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.bio.BioResultShow"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.history.HistoryActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.NewsActivityMain"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.ShowDetailActivity"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
<activity android:name="com.example.news.setting"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar"/>
</application>
</manifest>
Case1:When i ran above code in android 2.2 i seen a menu of image that made from gridview
and when i click on every item all image about this item shown.(in this case all result is OK)
Case2:But when I ran same code in android 4.2
by click on item (for view all image about it) my program become exit without any forceClose
for ex: when i click on image gallary_amir i expect that a gridview of image from ImageGroup7
Why?How i can fix Case2?
You said that you don't receive any force close, thereby no LogCat. What I would say is since you are checking on Android 4.2 which is API level 17, try to make your android:targetSdkVersion="" as 17 instead of 16 and see if you receiver any errors in LogCat. If you read about android:targetSdkVersion, it says:
If the API level of the platform is higher than the version declared by your app's targetSdkVersion, the system may enable compatibility behaviors to ensure that your app continues to work the way you expect.
Android tries to enable those compatibility behaviors when you test on higher version that targeted. There might be some function call or some other thing which got changed in API version 17 and is behaving in appropriately.
Other point is that try to see in your code that which thing have been depreciated for API 17 and have been used in your code. Using upto date stuff is always recommended.
Hope this helps in some way.

Showing activity from onCreate

Problem Description
I have two activities in my application MainActivity and BannerActivity. From the main activity I start BannerActivity in onCreate method. But I first I see MainActivity screen for a second and then BannerActivity screen.
Question
How I can do so that BannerActivity will be shown first and after countdown timer will stop and BannerActivity will close after that MainActivity come to the screen.
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Show banner activity for several seconds then close it. */
Intent bannerIntent = new Intent(MainActivity.this, BannerActivity.class);
this.startActivity(bannerIntent);
}
};
BannerActivity
public class BannerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
/* Make banner fullscreen. */
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
/* Launch count down timer for several seconds. */
CountDownTimer countDownTimer = new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished) { /* Not used. */ }
#Override
public void onFinish() {
BannerActivity.this.finish();
}
}.start();
}
#Override
public void onBackPressed() {
/* Lock back button presses. */
super.onBackPressed();
}
};
You need a SplashScreen:
http://www.thiagorosa.com.br/en/tutorial/part01-splash-screen
public class GameSplash extends Activity {
// time to wait on the splash screen
private static final int SPLASH_SCREEN_DELAY = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread() {
#Override
public void run() {
try {
// do any heavy initialization here
// wait a few seconds before going to the next screen
sleep(SPLASH_SCREEN_DELAY);
}
catch (InterruptedException e) {
}
catch (Exception e) {
}
finally {
// start the level selection screen
Intent intentSelect = new Intent(GameSplash.this, GameSelect.class);
startActivity(intentSelect);
}
}
}.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// ignore any key press on the splash screen
return true;
}
}
Run first BannerActivity and in the contdown run MainActivity rather than BannerActivity.this.finish();
You can start with BannerActivity and then when the time expires you go to MainActivity and clear the history stack by using this intent flag (so that you can't go back to the BannerActivity using the back button).
Intent.FLAG_ACTIVITY_CLEAR_TASK
Swap the activites on the Manifest to decide which activity is run first :
<activity
android:name="com.yourpackagename.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.yourpackagename.BannerActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The BannerActivity should have the <intent-filter> tag and set as Main and Launcher as the example. This will make Banner activity as the Initial Activity when you start your application.
After that you can just implement countdowntimer and start MainActivity when the timer ends.
Hope this helps, Good Luck ^^
try to use this way first need to load xml layout
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
or try to put in manifest like
<activity
android:name=".BannerActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
>
you can do like this also in your Banner Activity
use this code in oncreate method in banner activity
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finish();
}
}, 2000);
You need splash screen. Try this:
Start BanerActivity first. And make its onCreate like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait < 5000) { //Wait of 5 seconds
sleep(500);
wait += 500;
}
} catch (Exception e) {
} finally {
Intent i = new Intent(BanerActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this helps.
the easiest solution is to make the BannerActivity the launcher activity and modify the CountDownTimer to be
#Override
public void onFinish()
{
Intent mainIntent = new Intent(this, MainActivity.class);
startActivity(mainIntent);
finish();
}
then adjust the manifest file to make the BannerActivity as the launcher activity and remove it from the MainActivity

Check if app is open during a GCM onMessage event?

I am wondering how to check if my application is open and currently visible to the user when receiving an onMessage() from GCM. At first, I was just using my own boolean isVisible, but then I realized this isn't reliable, because if the app isn't open, the object I use to access that flag is null. While this in itself could be used to see if the app is open, it seems a little bit messy. Is there a way in Android from a system level to somehow check if the application is currently open, and if the user is viewing the app? Keep in mind an app could technically be running, but not be visible, because a user has recently pressed the "home" button sending it to the background.
#Override
protected void onMessage(Context arg0, Intent arg1) {
String turn = intent.getExtras().getString("turn");
if (turn.equals("yours"){
if (/*app is open*/){ <------------------ what can go here?
// dont generate a notification
// display something in the game instead
}
else{
// generate notification telling player its their turn
}
}
}
I would use order broadcasts to do that.
In your onMessage method:
Intent responseIntent = new Intent("com.yourpackage.GOT_PUSH");
sendOrderedBroadcast(responseIntent, null);
In your Activity:
public class YourActivity extends Activity {
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Right here do what you want in your activity
abortBroadcast();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//.....
}
#Override
protected void onPause() {
unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter("com.yourpackage.GOT_PUSH");
filter.setPriority(2);
registerReceiver(mBroadcastReceiver, filter);
super.onResume();
}
}
The other BroadcastReceiver
public class SecondReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//In this receiver just send your notification
}
}
Manifest:
<activity
android:name=".YourActivity"
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=".SecondReceiver">
<intent-filter
android:priority="1">
<action
android:name="com.yourpackage.GOT_PUSH" />
</intent-filter>
</receiver>
Basically in the onMessage method you send an Intent which is first received by the BroadcastReceiver registered inside YourActivity if it is running and in foreground, otherwise it is received by the SecondReceiver.
Use SharedPreferences saving the boolean isVisible, and when you get the value from the preference you can add a default value.
SharedPreferences settings = context.getSharedPreferences("NAME_XXX", Activity.MODE_PRIVATE);
settings.getBoolean("visible", false);
What I always do is have a reference to the current Activity.
I set the current Activity in every onResume to this and set it to null in every onPause.
If the current Activity is null then the app is not open. If it's not null you can see if the correct Activity is open and deliver it to that Activity.
GCMIntentService:
public static Activity currentActivity;
public static final Object CURRENTACTIVIYLOCK = new Object();
#Override
protected void onHandleIntent(Intent intent) {
synchronized(CURRENTACTIVIYLOCK) {
if (currentActivity != null) {
if (currentActivity.getClass() == CorrectActivity.class) {
CorrectActivity act = (CorrectActivity)currentActivity;
act.runOnUiThread(new Runnable() {
public void run() {
// Notifiy activity
}
});
} else {
// show notification ?
}
} else {
// show notification
}
}
}
CorrectActivity:
#Override
protected void onResume() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = this;
}
}
super.onResume();
}
#Override
protected void onPause() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = null;
}
super.onPause();
}
The thing that worked for me:
Create a final Class Constants, inside it, create static varaiable:
public final class Constants{
public static AppCompatActivity mCurrentActivity;
}
Now, on each on resume of your activties say:
#Override
protected void onResume() {
super.onResume();
Constants.mCurrentActivity = this;
}
When receieving notification, check if current activity is null, if its null, application is not opened, if activity isn't null, you can check things like:
if(Constants.mCurrentActivity instanceof MainActivity){
((MainActivity) Constants.mCurrentActivity).yourPublicMethodOrStaticObject;
}

Categories