start an activity from a TimerTask class - java

How can I start an activity in another class. It's in eclipse. It is just for start Main activity after a while.
public class FirstShow extends ActionBarActivity {
#SuppressLint("ShowToast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_show);
Timer tm;
tm = new Timer();
ttask task = new ttask();
tm.schedule(task, 30000);
}
}
class ttask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
FirstShow.class.startActivity());
}
}
I want to start another activity after a couple of seconds. How can I do that?

package com.example.teststart;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(FirstActivity.this,secondactivity.class);
startActivity(i);
}
}, 3000);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
}
package com.example.teststart;
import android.app.Activity;
import android.os.Bundle;
public class secondactivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactvity);
}
}
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.teststart.FirstActivity"
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.teststart.secondactivity"
android:label="#string/app_name" />
</application>

Friend if you want normally want to start activity after few second than use my code:----->
Thread thread = new Thread() {
public void run() {
try {
sleep(3*1000);
Intent i=new Intent(getBaseContext(),ManuList.class);
startActivity(i);
finish();
} catch (Exception e) {
}
}
};
thread.start();
}

public class FirstShow extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_show);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(FirstShow.this,secondactivity.class);
startActivity(i);
}
}, 3000);
}
}

Related

Null exception starting activity with intent

I'm receiving an exception that equals null when attempting to create a new activity using Intent. Basically my program terminates when I try to create this new Activity i.e. switch the screen the user sees to one with an animated treasure box (png files from xml, which works when they are run from the MainActivity).
Here is a picture from Android Studio of the error I am receiving:
I'm developing a Vuzix M100 application on a device running vr4.0.4.
Here are the two activities I am running:
MainActivity.java
package com.rit.se.treasurehuntvuz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
try {
Intent showTreasureIntent = new Intent(this, ShowTreasureActivity.class);
startActivity(showTreasureIntent);
}
catch(Exception exception) {
Log.e("MainActivity", exception.getMessage());
}
}
}
ShowTreasureActivity.java
package com.rit.se.treasurehuntvuz;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class ShowTreasureActivity extends AppCompatActivity {
private ImageView treasureImage;
private AnimationDrawable treasureAnimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showtreasure);
treasureImage = (ImageView)findViewById(R.id.treasureAnimationView);
treasureImage.setBackgroundResource(R.drawable.anim_treasure);
treasureAnimation = (AnimationDrawable) treasureImage.getBackground();
treasureAnimation.setOneShot(true);
}
#Override
public void onWindowFocusChanged (boolean hasFocus)
{
treasureAnimation.start();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onBackPressed() {
}
}
Thanks to #Joel Duggan, it turned out I was lacking an entry in the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rit.se.treasurehuntvuz">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowTreasureActivity">
</activity>
</application>
</manifest>

Display splashscreen & then AppIntro(First time launch) than mainactivity not working

I have made android app in which onLaunch I want to show SplashScreen for 3 second & then AppInro(If First time launch in slide) & then MainActivity launches. Actually I have done made splashscreen activity at the end but I set it up all properly but now After splashScreen MainActivity Starts directly. AppIntro not showing(Even in first time launch as well) Before adding SplashScreen activity AppIntro was working fine.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.introslider">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SpashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="Order Medicines"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="info.androidhive.welcomeslider.MainActivity"
//In above line code it shows Can not resolve symbol MainActivity
android:label="#string/title_activity_splash"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
SplashScreen
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
AppIntro(WelcomeActivity)
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3,
R.layout.welcome_slide4};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
You are never opening WelcomeActivity - you open MainActivity directly from SplashActivity, so PrefManager is never queried.
What you should do in SplashActivity is:
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SplashScreen.this, MainActivity.class)
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
And remove all first time launch checking code from WelcomeActivity.
You didn't initialize prefManager, Try initializing it first.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SpashScreen extends Activity {
private PrefManager prefManager;
// Splash screen timer
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// HERE prefManager INITIALIZED
prefManager = getPreferences(Context.MODE_PRIVATE);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i;
if (prefManager.isFirstTimeLaunch()) {
i = new Intent(SpashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else {
i = new Intent(SpashScreen.this, MainActivity.class);
}
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
You didn't initialize prefManager,this is the right way
this is worked for me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
try {
int netStatus = NetworkUtil.getConnectivityStatus(getBaseContext());
if (netStatus == 0) {
Intent intent = new Intent(SplashScreen.this,NoInternetActivity.class);
startActivity(intent);
finish();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
PrefManager prefManager = new PrefManager(getApplicationContext());
// This method will be executed once the timer is over
// Start your app main activity
if(prefManager.isFirstTimeLaunch()){
intent = new Intent(SplashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(true);
}else {
intent = new Intent(SplashScreen.this,MainActivity.class);
}
startActivity(intent);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}catch (RuntimeException e){
e.printStackTrace();
}
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}

Need a new solution for disabling the home, menu buttons in android

I have searched a lot and tried nearly everything and nothing worked for me .
I just want to disable the home and the menu buttons.
here is the LockScreenActivity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mehuljoisar.lockscreen.utils.LockscreenService;
import com.mehuljoisar.lockscreen.utils.LockscreenUtils;
public class LockScreenActivity extends Activity implements
LockscreenUtils.OnLockStatusChangedListener {
// User-interface
private Button btnUnlock;
private Button button1;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private ImageButton button10;
private TextView textView;
private RelativeLayout myView;
// Member variables
private LockscreenUtils mLockscreenUtils;
// Set appropriate flags to make the screen appear over the keyguard
#Override
public void onAttachedToWindow() {
this.getWindow().setType(
WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
);
super.onAttachedToWindow();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_lockscreen);
init();
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.button5);
button6=(Button)findViewById(R.id.button6);
button7=(Button)findViewById(R.id.button7);
button8=(Button)findViewById(R.id.button8);
button9=(Button)findViewById(R.id.button9);
button10=(ImageButton)findViewById(R.id.button10);
textView=(TextView)findViewById(R.id.textView1);
myView=(RelativeLayout)findViewById(R.id.layout);
// Ask the System Bar to hide
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"8");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"5");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"2");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"7");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"4");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"9");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"3");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"6");
}
});
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(textView.getText().toString().length()>0)
// TODO Auto-generated method stub
textView.setText(textView.getText().toString().substring(0, textView.getText().toString().length()-1));
}
});
// unlock screen in case of app get killed by system
if (getIntent() != null && getIntent().hasExtra("kill")
&& getIntent().getExtras().getInt("kill") == 1) {
enableKeyguard();
unlockHomeButton();
} else {
try {
// disable keyguard
disableKeyguard();
// lock home button
lockHomeButton();
// start service for observing intents
startService(new Intent(this, LockscreenService.class));
// listen the events get fired during the call
StateListener phoneStateListener = new StateListener();
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
}
}
}
private void init() {
mLockscreenUtils = new LockscreenUtils();
btnUnlock = (Button) findViewById(R.id.btnUnlock);
btnUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// unlock home button and then screen on button press
if(textView.getText().toString().equals("1234"))
unlockHomeButton();
}
});
}
// Handle events of calls and unlock screen if necessary
private class StateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
unlockHomeButton();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_IDLE:
break;
}
}
};
// Don't finish Activity on Back press
#Override
public void onBackPressed() {
return;
}
// Handle button clicks
#Override
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (keyCode == KeyEvent.KEYCODE_POWER)
|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
return true;
}
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
return false;
}
return true;
}
// handle the key press events here itself
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
|| (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
return false;
}
if ((event.getKeyCode() == KeyEvent.KEYCODE_HOME)) {
return false;
}
return false;
}
// Lock home button
public void lockHomeButton() {
mLockscreenUtils.lock(LockScreenActivity.this);
}
// Unlock home button and wait for its callback
public void unlockHomeButton() {
mLockscreenUtils.unlock();
}
// Simply unlock device when home button is successfully unlocked
#Override
public void onLockStatusChanged(boolean isLocked) {
if (!isLocked) {
unlockDevice();
}
}
#Override
protected void onStop() {
super.onStop();
unlockHomeButton();
}
#SuppressWarnings("deprecation")
private void disableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.disableKeyguard();
}
#SuppressWarnings("deprecation")
private void enableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.reenableKeyguard();
}
//Simply unlock device by finishing the activity
private void unlockDevice()
{
finish();
}
}
and here is my LockscreenIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.LockScreenActivity;
import com.mehuljoisar.lockscreen.R;
public class LockscreenIntentReceiver extends BroadcastReceiver {
// Handle actions and display Lockscreen
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)
|| intent.getAction().equals(Intent.ACTION_SCREEN_ON)
|| intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
start_lockscreen(context);
}
}
// Display lock screen
private void start_lockscreen(Context context) {
Intent mIntent = new Intent(context, LockScreenActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
and here is my LockscreenService.java
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.provider.SyncStateContract.Constants;
import android.support.v4.app.NotificationCompat;
import com.mehuljoisar.lockscreen.R;
public class LockscreenService extends Service {
private BroadcastReceiver mReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockscreenIntentReceiver();
registerReceiver(mReceiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
// Unregister receiver
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
and here is my LockscreenUtils.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.R;
public class LockscreenUtils {
// Member variables
private OverlayDialog mOverlayDialog;
private OnLockStatusChangedListener mLockStatusChangedListener;
// Interface to communicate with owner activity
public interface OnLockStatusChangedListener
{
public void onLockStatusChanged(boolean isLocked);
}
// Reset the variables
public LockscreenUtils() {
reset();
}
// Display overlay dialog with a view to prevent home button click
public void lock(Activity activity) {
if (mOverlayDialog == null) {
mOverlayDialog = new OverlayDialog(activity);
mOverlayDialog.show();
mLockStatusChangedListener = (OnLockStatusChangedListener) activity;
}
}
// Reset variables
public void reset() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
}
}
// Unlock the home button and give callback to unlock the screen
public void unlock() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
if(mLockStatusChangedListener!=null)
{
mLockStatusChangedListener.onLockStatusChanged(false);
}
}
}
// Create overlay dialog for lockedscreen to disable hardware buttons
private static class OverlayDialog extends AlertDialog {
public OverlayDialog(Activity activity) {
super(activity, R.style.OverlayDialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
getActionBar().setDisplayHomeAsUpEnabled(false);
params.type = LayoutParams.TYPE_SYSTEM_ERROR;
params.dimAmount = 0.0F;
params.width = 0;
params.height = 0;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
getWindow().setFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_NOT_TOUCH_MODAL,
0xffffff);
setOwnerActivity(activity);
setCancelable(false);
}
// consume touch events
public final boolean dispatchTouchEvent(MotionEvent motionevent) {
return true;
}
}
}
last but not least .. here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mehuljoisar.lockscreen"
android:versionCode="3"
android:versionName="1.2" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.mehuljoisar.lockscreen.LockScreenActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Holo.NoActionBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".utils.LockscreenService" >
</service>
<receiver
android:name=".utils.LockscreenIntentReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Use below method for hiding home/menu button:
getActionBar().setDisplayHomeAsUpEnabled(false)
Or use
getActionBar().setHomeButtonEnabled (false)
to disable interaction with the home/up affordance.

How do I call my NoteMain class when I click on the "Notes" Button in my android app

As above. I'm to sure what I'm doing wrong. Here is the code for the MainActivity.java and the code for the NoteMain.java When I click on the Notes button on the home screen when the app loads it says Unfortunately,(app name) has stopped.
I don't know why? Any help is appreciated.
Thanks in advance
MainActivity:
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button buttonConverter;
Button buttonCalculator;
Button buttonNotePad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ConvertBtn = (Button) findViewById(R.id.butonConverter);
ConvertBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CentInch.class);
startActivity(intent);
}
});
Button CalcBtn = (Button) findViewById(R.id.buttonCalc);
CalcBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Calculator.class);
startActivity(intent);
}
});
Button NoteBtn = (Button) findViewById(R.id.buttonNotes);
NoteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,NoteMain.class);
startActivity(intent);
}
});
}
public void setupConverterButton(){
buttonConverter = (Button) findViewById(R.id.butonConverter);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void CentToInch(){
buttonConverter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class centClass = Class
.forName("com.qub.buildersbuddy.CentInch");
Intent myintent = new Intent(MainActivity.this,centClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupCalculatorButton(){
buttonCalculator = (Button) findViewById(R.id.buttonCalc);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Calculator(){
buttonCalculator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class calcClass = Class
.forName("com.qub.buildersbuddy.Calculator");
Intent myintent = new Intent(MainActivity.this,calcClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
public void setupNotesButton(){
buttonNotePad = (Button) findViewById(R.id.buttonNotes);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Notes(){
buttonNotePad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class NoteMain = Class
.forName("com.qub.buildersbuddy.NoteMain");
Intent myintent = new Intent(MainActivity.this,NoteMain);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
}
NoteMain
package com.qub.buildersbuddy;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class NoteMain extends Activity implements OnItemClickListener, OnClickListener {
private SharedPreferences spNotes;
private ArrayList<Note> notes;
private Button addNote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_main);
this.addNote = (Button) findViewById(R.id.addNoteButton);
this.addNote.setOnClickListener(this);
spNotes = getSharedPreferences("notes", Context.MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
showNotes();
ListView list = (ListView) findViewById(R.id.listNotes);
CustomAdapter aa = new CustomAdapter(this, getLayoutInflater(), this.notes, spNotes);
list.setAdapter(aa);
list.setOnItemClickListener(this);
}
private void showNotes() {
this.notes = new ArrayList<Note>();
Map map = spNotes.getAll();
for (Object o : map.entrySet()) {
Entry e = (Entry<String, String>) o;
this.notes.add(new Note((String)e.getKey(), (String)e.getValue()));
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Intent intent = new Intent(this, NoteActivity.class);
intent.putExtra("title", this.notes.get(position).getTitle());
intent.putExtra("text", this.notes.get(position).getText());
startActivity(intent);
}
#Override
public void onClick(View arg0) {
Intent intent = new Intent(this, NoteActivity.class);
startActivity(intent);
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qub.buildersbuddy"
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.qub.buildersbuddy.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>
<activity
android:name="com.qub.buildersbuddy.CentInch"
android:label="#string/title_activity_cent_inch" >
</activity>
<activity
android:name="com.qub.buildersbuddy.Calculator"
android:label="#string/title_activity_calculator" >
</activity>
<activity
android:name="com.qub.buildersbuddy.NotePad"
android:label="#string/title_activity_note" >
</activity>
</application>
</manifest>
Its probably because you don't have the NoteMain activity defined in your Manifest.
<activity
android:name="com.qub.buildersbuddy.NoteMain"
android:label="#string/title_activity_note" >
</activity>

Thread within a Splash Screen

package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity {
private Intent myintent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
myintent = new Intent(this, MainActivity.class);
splashScreen(1000); }
public void splashScreen (final int x)
{
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(x);
} catch (InterruptedException e) {
e.printStackTrace();
}
startActivity(myintent);
finish();
}
}).run();
}
}
There's the code, and here is the problem : the SplashScreen do not get the content view of the splash XML layout file... Now, I have my suspicions that it is a thread problem and that somehow the thread is executed before the setContentView method although that method is located before the run method of the Thread in code, so it's illogical that I'm thinking this way but I'm like running out of reasons for this Splash Screen not to work
Change thread.run() to thread.start(): http://www.javafaq.nu/java-article1131.html
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(x);
} catch (InterruptedException e) {
e.printStackTrace();
}
startActivity(myintent);
finish();
}
}).start();
A better way to implement Splash:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
myintent = new Intent(this, MainActivity.class);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
startActivity(myintent);
finish();
}
}, 1000);
}
package com.echo.myatlsnookpaid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(3500);
// sleep(100);
}
catch(InterruptedException e){
e.printStackTrace();
} finally {
Intent openMain = new Intent(Splash.this, MainActivity.class);
startActivity(openMain);
finish();
}
}
};
timer.start();
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
and in your manifest, give the
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
filter to he splashactivity.

Categories