onCreate() and onPause() called incorrectly from other activities - android

My problem is that onCreate() and onPause() in a closed activity gets called when they shouldn't.
I the Start activity i call:
Intent intent = new Intent(this, SelectTransportActivity.class);
startActivity(intent);
this.finish();
when i want to start the SelectTransport activity.
But when i want to start the Stop Activity from the SelectTransport activity and i call
Intent i = new Intent(this, StopActivity.class);
startActivity(i);
this.finish();
I can see in the debugger that the onCreate() in the Start activity is called before the Stop activity starts.
Similarly, when I finishes the Stop activity, the onPause() in the Start activity is called, after which the Start activity starts.
Why are the onCreate() and onPause() called in the Start activity from the other activities when they shouldn't and I have finished the activity?
The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.greenenergy"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- Launching -->
<uses-permission android:name="android.permission.BATTERY_STATS" />
<!-- All probes -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Storage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Location probe -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".GreenEnergyApplication">
<service android:name="edu.mit.media.funf.FunfManager" >
<meta-data
android:name="default"
android:value="#string/default_pipeline" />
</service>
<receiver
android:name="edu.mit.media.funf.Launcher"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.DOCK_EVENT" />
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<activity
android:name="com.example.greenenergy.StartupActivity"
android:screenOrientation="portrait"
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.greenenergy.StartActivity"
android:screenOrientation="portrait"
android:label="#string/title_activity_start" >
</activity>
<activity
android:name="com.example.greenenergy.WaysActivity"
android:screenOrientation="portrait"
android:label="#string/title_activity_ways" >
</activity>
<activity
android:name="com.example.greenenergy.StopActivity"
android:screenOrientation="portrait"
android:label="#string/title_activity_stop">
</activity>
<activity
android:name="com.example.greenenergy.StatisticsActivity"
android:screenOrientation="portrait"
android:label="#string/title_activity_statistics">
</activity>
</application>
The Start activity:
public class StartActivity extends BaseActivity implements OnClickListener {
private Button bStart, bStats;
Controller controller;
GPSCollectorSingleton gpsCollectorSingleton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
autoDetect();
}
private void init() {
setContentView(R.layout.activity_main);
bStart = (Button) findViewById(R.id.bStart);
bStats = (Button) findViewById(R.id.bStatisticsStart);
bStart.setOnClickListener(this);
bStats.setOnClickListener(this);
controller = new Controller(); // Init controller
Database database = new Database(getApplicationContext());
controller.controlDatabase(database);
controller.createTable(); // Create table if not exist
gpsCollectorSingleton = GPSCollectorSingleton.getInstance(); // Init model
// Bind to the service, to create the connection with FunfManager
getApplicationContext().bindService(new Intent(this, FunfManager.class), funfManagerConn, BIND_AUTO_CREATE);
}
private void autoDetect() {
boolean auto = ((GreenEnergyApplication) getApplication()).getAutoPreference(getApplicationContext());
boolean started = ((GreenEnergyApplication) getApplication()).getStartPreference(getApplicationContext());
if (auto && !started) {
controller.enableAutoDetection(getApplicationContext(), gpsCollectorSingleton);
}
}
#Override
protected void onPause() {
super.onPause();
this.finish();
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.bStart:
startDataCollector();
break;
case R.id.bStatisticsStart:
intent = new Intent(this, StatisticsActivity.class);
startActivity(intent);
break;
}
}
private void startDataCollector() {
if (((GreenEnergyApplication) getApplication()).getStartPreference(getApplicationContext()) == false) {
controller.datahandlerObserver(getApplicationContext(), gpsCollectorSingleton); // Observer
((GreenEnergyApplication) getApplication()).setStartPreference(getApplicationContext(), true);
}
Intent intent = new Intent(this, WaysActivity.class);
startActivity(intent);
}
}
The SelectTransport activity:
public class SelectTransportActivity extends BaseActivity implements OnItemClickListener {
GridView gridview;
private static int DATABASE_ID_OFFSET = 2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ways);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
this.finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
((GreenEnergyApplication)getApplication()).setTransportationPreference(getApplicationContext(), arg2+DATABASE_ID_OFFSET);
Log.i("WayActivity",
"ARG0: " + arg0.toString() + " Arg1: " + arg1.toString() + " "
+ " Arg2: " + arg2 + " Arg3: " + arg3);
Intent i = new Intent(this, StopActivity.class);
startActivity(i);
}
}
The Stop activity:
public class StopActivity extends StartActivity implements OnClickListener, Observer {
Button stopButton, statsButton;
TextView statusTextView;
int distance, time, transportTypeEstimate, transportType;
int sessionStartTime = 0;
int sessionStartDistance = 0;
GPSCollectorSingleton gpsCollectorSingleton;
LocationData location;
boolean transportEstimation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GPSCollectorSingleton gps = GPSCollectorSingleton.getInstance();
if (((GreenEnergyApplication) getApplication()).getStartPreference(getApplicationContext()) == false) {
Log.i("STOP - STOP", "hasspeed");
stopDataCollector();
}
setContentView(R.layout.activity_stop);
stopButton = (Button) findViewById(R.id.bStop);
statsButton = (Button) findViewById(R.id.bStatisticsStop);
statusTextView = (TextView) findViewById(R.id.tvStatus);
stopButton.setOnClickListener(this);
statsButton.setOnClickListener(this);
gpsCollectorSingleton = GPSCollectorSingleton.getInstance(); // Init model
gpsCollectorSingleton.addObserver(this); // Observe on models state
initTransportTypeDetection();
}
/**
* Initializes estimating of transport type or manually chosen transport type
*/
private void initTransportTypeDetection() {
transportType = ((GreenEnergyApplication) getApplication())
.getTransportationPreference(getApplicationContext());
transportTypeEstimate = transportType;
if (transportType == TransportationDefinerSingleton.TRANSPORT_UNKNOWN) { // Start transport type estimation
TransportationDefinerSingleton transport = TransportationDefinerSingleton.getInstance(); // Get model
transport.addObservable(gpsCollectorSingleton); // Add observer for estimating transport type
transportEstimation = true;
} else { // Transport type manually specified
setSessionStartDistanceAndTime();
transportEstimation = false;
}
}
private void setSessionStartDistanceAndTime() {
Controller controller = new Controller();
Database database = new Database(getApplicationContext());
controller.controlDatabase(database);
sessionStartDistance = controller.getDistanceFromID(transportType);
sessionStartTime = controller.getTimeFromID(transportType);
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.bStop:
stopDataCollector();
break;
case R.id.bStatisticsStop:
intent = new Intent(this, StatisticsActivity.class);
startActivityForResult(intent, -1);
break;
}
}
private void stopDataCollector() {
((GreenEnergyApplication) getApplication()).setTransportationPreference(getApplicationContext(),
TransportationDefinerSingleton.TRANSPORT_UNKNOWN);
((GreenEnergyApplication) getApplication()).setStartPreference(getApplicationContext(), false);
gpsCollectorSingleton.deleteObservers(); // Delete all observers
Controller controller = new Controller();
Database database = new Database(getApplicationContext());
controller.controlDatabase(database);
// Get unknown data. From estimate of transport type or data collected while deciding transport type.
int distance = controller.getDistanceFromID(TransportationDefinerSingleton.TRANSPORT_UNKNOWN);
int time = controller.getTimeFromID(TransportationDefinerSingleton.TRANSPORT_UNKNOWN);
if (transportEstimation) { // Estimate
controller.updateTable(transportTypeEstimate, distance, time);
} else { // Manually chosen transport type
controller.updateTable(transportType, distance, time);
}
controller.resetTable(TransportationDefinerSingleton.TRANSPORT_UNKNOWN);
Intent intent = new Intent(this, StartActivity.class);
startActivity(intent);
this.finish();
}
#Override
public void update(Observable observable, Object data) {
Controller controller = new Controller();
Database database = new Database(getApplicationContext());
controller.controlDatabase(database);
transportTypeEstimate = getTransportType();
distance = controller.getDistanceFromID(transportType) - sessionStartDistance;
time = controller.getTimeFromID(transportType) - sessionStartTime;
location = (LocationData) data;
runOnUiThread(new Runnable() {
#Override
public void run() {
String transportName = getTransportName(transportTypeEstimate);
statusTextView.setText("Transport type: " + transportName + " Distance: " + distance + " Time: " + time
+ "\nTimeStamp: " + location.getTime() + "\nSpeed: " + location.getSpeed()
+ " Seconds since last: " + location.getSecondsSinceLastSample());
}
});
}
private int getTransportType() {
if (transportEstimation) {
TransportationDefinerSingleton transport = TransportationDefinerSingleton.getInstance();
Controller controller = new Controller();
controller.controlTransportationDefinerSingleton(transport);
transportTypeEstimate = controller.getTransportType();
}
return transportTypeEstimate;
}
private String getTransportName(int type) {
switch (type) {
case TransportationDefinerSingleton.TRANSPORT_UNKNOWN:
return "Unknown";
case TransportationDefinerSingleton.TRANSPORT_WALK:
return "Walking";
case TransportationDefinerSingleton.TRANSPORT_BIKE:
return "Bike";
case TransportationDefinerSingleton.TRANSPORT_CAR:
return "Car";
case TransportationDefinerSingleton.TRANSPORT_BUS:
return "Bus";
case TransportationDefinerSingleton.TRANSPORT_TRAIN:
return "Train";
case TransportationDefinerSingleton.TRANSPORT_MOTORCYCLE:
return "Motor Cycle";
case TransportationDefinerSingleton.TRANSPORT_CARPOOL:
return "Carpool";
}
return "";
}
}
The Base activity, which is the superclass for the other activities. It just sets up the option menu and other basic stuff.
public class BaseActivity extends Activity {
private Controller controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GPSCollectorSingleton gpsCollectorSingleton = GPSCollectorSingleton.getInstance(); // Init model
controller = new Controller();
controller.controlGPSCollectorSingleton(gpsCollectorSingleton); // Init controller
}
protected ServiceConnection funfManagerConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("OnServiceConnected", "MainActivity");
controller.onServiceConnected(service);
}
#Override
public void onServiceDisconnected(ComponentName name) {
controller.onServiceDisconnected();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
disableService();
closeActivity();
return true;
case R.id.action_clear:
Database database = new Database(getApplicationContext());
database.dropTable();
return true;
case R.id.action_toggle_auto:
if (item.isChecked()) {
item.setChecked(false);
((GreenEnergyApplication) getApplication()).setAutoPreference(getApplicationContext(), false);
} else {
item.setChecked(true);
((GreenEnergyApplication) getApplication()).setAutoPreference(getApplicationContext(), true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (((GreenEnergyApplication) getApplication()).getAutoPreference(getApplicationContext()) == true) {
menu.findItem(R.id.action_toggle_auto).setChecked(true);
}
return true;
}
/**
* Disables the service and the pipeline
*/
private void disableService() {
controller.disablePipeline(); // Disable pipeline
boolean isBound = false;
isBound = getApplicationContext().bindService(new Intent(getApplicationContext(), FunfManager.class),
funfManagerConn, BIND_AUTO_CREATE);
if (isBound) {
getApplicationContext().unbindService(funfManagerConn); // Disable
// service
}
}
private void closeActivity() {
this.finish();
}
}

Let's start with the easy things: Your StopActivity extends StartActivity
public class StopActivity extends StartActivity {...
It should either extend BaseActivity or a call to super.onCreate() will run the code in StartActivity.onCreate().

Related

Activity.finish() finishes all activities

I have two Activities: MenuScreen and Main. MenuScreen starts Main and finishes himself.
Intent intent = new Intent(this, sp.overview.Main.class);
//All extra intent values
startActivity(intent);
finish();
However when i finish Main and start MenuScreen, it also finishes MenuScreen. Note that the finish is called in the SurfaceView of Main
Intent i = new Intent(context, MenuScreen.class);
((Main)context).finish();
context.startActivity(i);
But I just want to finish Main and go back to MenuScreen. What am I doing wrong?
Manifest:
<application
android:name=".Global"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:largeHeap="true">
<activity
android:name=".MenuScreen"
android:label="#string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main"
android:label="#string/title_activity_menu_screen"
android:screenOrientation="landscape">
</activity>
</application>
MenuScreen:
public class MenuScreen extends Activity {
int subject_value = 0;
boolean training = false;
Global global;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
global = (Global)getApplicationContext();
this.subject_value = global.getSubject();
//Set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_menu_screen);
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
#Override
protected void onRestart()
{
super.onRestart();
this.subject_value = global.getSubject();
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
#Override
protected void onStart()
{
super.onStart();
this.subject_value = global.getSubject();
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
#Override
protected void onResume()
{
super.onResume();
this.subject_value = global.getSubject();
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
public void StillOne(View view){
sentExtra(Setting.Layout.Still, Setting.FrameSkip.One);
}
public void sentExtra(Setting.Layout layout, Setting.FrameSkip frameSkip)
{
Intent intent = new Intent(this, sp.overview.Main.class);
intent.putExtra("LAYOUT", layout.getValue());
intent.putExtra("FRAMESKIP", frameSkip.getValue());
intent.putExtra("SUBJECT", this.subject_value);
intent.putExtra("TRAINING", this.training);
finish();
startActivity(intent);
}
public void MotionThree(View view) {
sentExtra(Setting.Layout.Motion, Setting.FrameSkip.Three);
}
public void MotionTwo(View view) {
sentExtra(Setting.Layout.Motion, Setting.FrameSkip.Two);
}
public void MotionOne(View view) {
sentExtra(Setting.Layout.Motion, Setting.FrameSkip.One);
}
public void StillThree(View view) {
sentExtra(Setting.Layout.Still, Setting.FrameSkip.Three);
}
public void StillTwo(View view) {
sentExtra(Setting.Layout.Still, Setting.FrameSkip.Two);
}
public void Plus(View view) {
this.subject_value++;
global.setSubject(this.subject_value);
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
public void Minus(View view) {
this.subject_value--;
global.setSubject(this.subject_value);
TextView t = (TextView)findViewById(R.id.subject_value);
t.setText(String.valueOf(this.subject_value));
}
public void Training(View view) {
this.training = !this.training;
android.widget.Button b = (android.widget.Button)findViewById(R.id.training);
b.setText("Training: " + String.valueOf(this.training));
}
}
Main:
public class Main extends Activity implements SensorEventListener {
private Overview overview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//turn the title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
Intent it = getIntent();
int layout = it.getIntExtra("LAYOUT", 1);
int frameskip = it.getIntExtra("FRAMESKIP", 1);
int subject = it.getIntExtra("SUBJECT", 0);
boolean training = it.getBooleanExtra("TRAINING", false);
Setting s = new Setting(Setting.Layout.getSetting(layout), Setting.FrameSkip.getSetting(frameskip), training);
overview = new Overview(this, s, subject);
setContentView(overview);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Overview:
public class Overview extends SurfaceView implements SurfaceHolder.Callback{
private MainLoop loop;
private static Context context;
public int Subject;
public Setting state;
public Overview(Context context, Setting state, int subject) {
super(context);
// Set the context;
this.context = context;
this.state = state;
this.Subject = subject;
//add the callback to the SurfaceHolder to intercept events;
getHolder().addCallback(this);
getHolder().setFormat(PixelFormat.RGBA_8888);
//init the MainLoop
loop = new MainLoop(getHolder(), this, this.state);
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
if(!loop.equals(null))
{
int index = event.getActionIndex();
int id = event.getPointerId(index);
ProgressManager p = loop.progressManager;
PointF pos = null;
switch (event.getActionMasked())
{
case MotionEvent.ACTION_UP:
switch (p.state) {
case Start:
if (!p.loading)
p.state = ProgressManager.Progress.Image;
break;
case Image:
break;
case Pause:
p.state = ProgressManager.Progress.Overview;
break;
case Overview:
pos = new PointF(event.getX(0), event.getY(0));
if(p.trueButton.collide(pos)) {
p.answer = true;
if(p.setting.layout == Setting.Layout.Motion)
p.frameLoader.stop();
p.state = ProgressManager.Progress.Result;
}
if(p.falseButton.collide(pos)) {
p.answer = false;
if(p.setting.layout == Setting.Layout.Motion)
p.frameLoader.stop();
p.state = ProgressManager.Progress.Result;
}
break;
case Result:
if(!p.saving && p.saved) {
Intent i = new Intent(context, MenuScreen.class);
context.startActivity(i);
((Main)context).finish();
}
break;
}
break;
default:break;
}
}
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while(retry)
{
try
{
loop.setRunning(false);
loop.join();
retry = false;
// Properly turn of the process (otherwise it creates multiple instances of all objects...)
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
loop.setRunning(true);
loop.start();
}
}
Why are you doing finish MenuScreen? Just start Main activities and do not call finish() in your code. It's will work fine.
But Your code is wrong!
Instead of this code:
Intent i = new Intent(context, MenuScreen.class);
((Main)context).finish();
context.startActivity(i);
Do this:
Intent i = new Intent(context, MenuScreen.class);
context.startActivity(i);
((Main)context).finish();
Hope this help :)
You are finishing your activity and after that u try to open activity(when there is no activity).
replace this lines..
Intent i = new Intent(context, MenuScreen.class);
((Main)context).finish();
context.startActivity(i);
with this..
Intent i = new Intent(context, MenuScreen.class);
context.startActivity(i);
((Main)context).finish();

Kiosk mode is not working.?

I am creating sample app with kiosk mode in my app to check that is kiosk mode work or not.?. But in sample app kiosk mode is not working. I means after screen goes off activity is not starting.
I have taken this from [http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/][here]
THis is my main activity
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(!hasFocus) {
// Close every kind of system dialog
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
THis is my Application class
public class AppContext extends Application {
private AppContext instance;
private PowerManager.WakeLock wakeLock;
private OnScreenOffReceiver onScreenOffReceiver;
PowerManager pm;
#Override
public void onCreate() {
super.onCreate();
instance = this;
registerKioskModeScreenOffReceiver();
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
startKioskService();
}
private void registerKioskModeScreenOffReceiver() {
// register screen off receiver
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
onScreenOffReceiver = new OnScreenOffReceiver();
registerReceiver(onScreenOffReceiver, filter);
}
public PowerManager.WakeLock getWakeLock() {
if(wakeLock == null) {
// lazy loading: first call, create wakeLock via PowerManager.
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakeup");
}
return wakeLock;
}
private void startKioskService() { // ... and this method
startService(new Intent(this, KioskService.class));
}
}
This is receiver class
public class OnScreenOffReceiver extends BroadcastReceiver {
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
#Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())){
AppContext ctx = (AppContext) context.getApplicationContext();
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
wakeUpDevice(ctx);
}
}
}
private void wakeUpDevice(AppContext context) {
PowerManager.WakeLock wakeLock = context.getWakeLock(); // get WakeLock reference via AppContext
if (wakeLock.isHeld()) {
wakeLock.release(); // release old wake lock
}
// create a new wake lock...
wakeLock.acquire();
// ... and release again
wakeLock.release();
}
private boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
}
THis is Service class
public class KioskService extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // periodic interval to check in seconds -> 2 seconds
private static final String TAG = KioskService.class.getSimpleName();
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
Log.i(TAG, "Stopping service 'KioskService'");
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Starting service 'KioskService'");
running = true;
ctx = this;
// start a thread that periodically checks if your app is in the foreground
t = new Thread(new Runnable() {
#Override
public void run() {
do {
handleKioskMode();
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
Log.i(TAG, "Thread interrupted: 'KioskService'");
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
private void handleKioskMode() {
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
// is App in background?
if(isInBackground()) {
restoreApp(); // restore!
}
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
// Restart activity
Intent i = new Intent(ctx, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
}
public boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kioskmode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:name=".AppContext"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.kioskmode.KioskService" android:exported="false"></service>
<receiver android:name="com.example.kioskmode.OnScreenOffReceiver" android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.app.action.SCREEN_OFF" />
<action android:name="android.app.action.SCREEN_ON" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Any one can solve this... for me..?? Thanks in advance..
Your method isKioskModeActive is always false. So it won't restore your app.

AIDL, bind and unbind IExtendedNetworkService Service

I use AIDL interface IExtendedNetworkService to get USSD code. But application only work after reboot device. I tried bindservice after install app but it didn't work. So my problem is how way to bind service without reboot device . This is my code:
interface:
package com.android.internal.telephony;
interface IExtendedNetworkService {
void setMmiString(String number);
CharSequence getMmiRunningText();
CharSequence getUserMessage(CharSequence text);
void clearMmiString();
}
Service
public class CDUSSDService extends Service {
private String TAG = "THANG-NGUYEN";
private boolean mActive = false;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
// activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
} else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if (mActive == true) {
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if (mActive == false) {
// listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
// listener is active, so broadcast data and suppress it from
// default behavior
// build data to send with intent for activity, format URI as per
// RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(
getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(
getBaseContext().getString(R.string.uri_param_name),
text.toString()).build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
public void onCreate() {
Log.i(TAG, "called onCreate");
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "called onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
// the insert/delete intents will be fired by activity to
// activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(
getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path),
PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
MainActivity:
public class MainActivity extends Activity {
private Button btnCheckUSSD;
private Context mContext;
private IExtendedNetworkService mService;
private EditText inputUSSD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnCheckUSSD = (Button) findViewById(R.id.btn_check);
inputUSSD = (EditText) findViewById(R.id.input_ussd);
btnCheckUSSD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!inputUSSD.getText().toString().isEmpty()) {
Intent service = new Intent(
"com.android.ussd.IExtendedNetworkService");
bindService(service, mConnecton, Context.BIND_AUTO_CREATE);
startActivity(new Intent("android.intent.action.CALL", Uri
.parse("tel:" + inputUSSD.getText().toString()
+ Uri.encode("#"))));
}
}
});
}
ServiceConnection mConnecton = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
mService = IExtendedNetworkService.Stub
.asInterface((IBinder) iBinder);
}
};
protected void onDestroy() {
super.onDestroy();
Log.d("THANG-NGUYEN", "onDestroy");
unbindService(mConnecton);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.example.checkussdcode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.example.checkussdcode.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>
<service
android:name="info.example.checkussdcode.service.UssdCodeService"
android:process=":remote" >
<intent-filter>
<action android:name="com.android.ussd.IExtendedNetworkService" >
</action>
</intent-filter>
</service>
<receiver android:name="info.example.checkussdcode.RebootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

Issue passing data from activity to service

'Below are my two classes which I'm trying to pass data from my activity to my service. I've passed to other Activities no problem but I when look for my extras in my IntentService it always comes back null. Any ideas what I'm doing incorrectly?
public class TestActivity extends Activity {
private Button mbutton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutton = (Button) this.findViewById(R.id.button1);
mbutton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("TestActivity", "onClick: starting srvice");
Intent intent = new Intent(TestActivity.this/*getApplicationContext()*/, MyService.class);
/*TestActivity.this.getApplicationContext().*/
intent.putExtra(MyService.PARAM_IN_NAME, ((EditText)findViewById(R.id.editText1)).getText());
intent.putExtra(MyService.PARAM_IN_JOB, ((EditText)findViewById(R.id.editText2)).getText());
intent.putExtra(MyService.PARAM_IN_BDAY, ((EditText)findViewById(R.id.editText3)).getText());
startService(intent);
}
});
}
}
This is my Service class which I'm trying to extract my data from activity.
public class MyService extends IntentService {
public static final String PARAM_IN_NAME = "name";
public static final String PARAM_IN_JOB = "job";
public static final String PARAM_IN_BDAY = "bday";
private String mJob;
private String mBday;
private String mName;
// --------------CONSTRUCTORS--------------
public MyService() {
super("MyServiceThread");
}
public MyService(String name) {
super(name);
}
// -------------OVERRIDE-------------
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy(){
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
mName = intent.getStringExtra(PARAM_IN_NAME);
mJob = intent.getStringExtra(PARAM_IN_JOB);
mBday = intent.getStringExtra(PARAM_IN_BDAY);
String result = "Name = " + mBday + " | Job = " + mJob + " | Bday = " + mBday;
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
This is also what I have for my Manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TestActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" android:enabled="true" />
Use bundle for sending the data to the service.
From the activity.
Bundle bundle = new Bundle();
bundle.putCharSequence("extraData", data);
myIntent.putExtras(bundle);
Receives in service.
Bundle bundle = intent.getExtras();
data = (String) bundle.getCharSequence("extraData");
Your code is looking fine.
Try after adding toString() when you get text from the EditText like this:
intent.putExtra(MyService.PARAM_IN_NAME, ((EditText)findViewById(R.id.editText1)).getText().toString());
I hand my data over like this to the receiving end
Bundle bundle = this.getIntent().getExtras();
String scan = bundle.getString("scan");
((TextView)findViewById(R.id.username)).setText(scan);

Android full screen not working when activity is launched by a service

So I am developing an alternate lockscreenapp
and I need to prevent clicking the notificationbar
so I try to run this app in fullscreenn
but when it is calle by a service the notificationbar is still their when it is called by the launcher it get invisible
Code:
public class app extends Activity {
TextView datum;
static TextView time;
static TextView temperature;
static ImageView weather_icon;
static TextView weather_refreshed;
static RelativeLayout refresh;
private static Context mContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.startService(new Intent(this, lockservice.class));
mContext = this;
//Date
datum = (TextView) findViewById(R.id.datum);
SimpleDateFormat sdf = new SimpleDateFormat("E dd MMM");
String currentDateandTime = sdf.format(new Date());
datum.setText(currentDateandTime);
//Time
time = (TextView) findViewById(R.id.clock);
Date date = new Date();
int hours = date.getHours();
String diplay_hours = String.valueOf(hours);
int minutes = date.getMinutes();
String diplay_minutes = String.valueOf(minutes);
if(hours < 10)
{
diplay_hours = "0"+String.valueOf(hours);
}
if(minutes < 10)
{
diplay_minutes = "0"+String.valueOf(minutes);
}
time.setText(String.valueOf(diplay_hours+":"+diplay_minutes));
//update
Thread myThread = new Thread(new UpdateThread());
myThread.start();
// Weather
temperature = (TextView) findViewById(R.id.weather_temp);
weather_icon = (ImageView) findViewById(R.id.weather_icon);
weather_refreshed = (TextView) findViewById(R.id.weather_refreshed);
refresh = (RelativeLayout) findViewById(R.id.relativeLayout1);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
weather.download();
}
});
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onAttachedToWindow()
{
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
#Override
public boolean onKeyDown(int iKeyCode, KeyEvent event)
{
if(iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME)
{
finish();
return true;
}
return false;
}
//update
public Handler updateHandler = new Handler(){
/** Gets called on every message that is received */
// #Override
public void handleMessage(Message msg) {
//Time
time = (TextView) findViewById(R.id.clock);
Date date = new Date();
int hours = date.getHours();
String diplay_hours = String.valueOf(hours);
int minutes = date.getMinutes();
String diplay_minutes = String.valueOf(minutes);
if(hours < 10)
{
diplay_hours = "0"+String.valueOf(hours);
}
if(minutes < 10)
{
diplay_minutes = "0"+String.valueOf(minutes);
}
time.setText(String.valueOf(diplay_hours+":"+diplay_minutes));
//weather
weather.display();
try
{
SharedPreferences weather = app.getContext().getSharedPreferences("weather",app.getContext().MODE_WORLD_READABLE);
app.weather_refreshed.setText(weather.getString("time",""));
}
catch(Exception x)
{
}
super.handleMessage(msg);
}
};
public class UpdateThread implements Runnable {
#Override
public void run() {
while(true){
long startTime = System.currentTimeMillis();
app.this.updateHandler.sendEmptyMessage(0); //handler
Thread.yield();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static Context getContext(){
return mContext;
}
#Override
public void onPause() {
super.onPause();
}
I also use Keyguard
the fullscreen is implemented in my manifest :
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".app"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="boot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service
android:name="lockservice"
android:process=":lockscreen"
android:icon="#drawable/ic_launcher"
android:label="Lockscreen">
</service>
<activity
android:name=".weather_update"
android:theme="#android:style/Theme.Translucent">
</activity>
</application>
I used full screen before same as your way and had some problems but didn't try launching the activity from service, try to apply full screen this way,
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(attrs);
just in case you need to exit full screen, you can do it this way,
WindowManager.LayoutParams attrs = getWindow().getAttributes();
attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setAttributes(attrs);
give it a shot, good luck!
It seems that this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); causes the issue.
Someone else suggests to delay that call: See Activity doesn't show in full screen.

Categories

Resources