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();
Related
I have a Service that when one function gives to me true it will start a new Activity but it takes like 5 seconds...
I've read about this issue, and I've found on StackOverflow this example to "avoid" this bug..
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
but sadly it doesn't start the Activity faster, I don't need to be inmmediate (better if it's possible), but I don't want to wait +5 seconds to launch the new Activity, do you knwo any trick to avoid this?
I'm using PendingIntent because I've found that guy that said that it should solve this issue :
Starting an activity from a service after HOME button pressed without the 5 seconds delay
Note
If I press back button it launch it autommatically, 0 delay, but I'm looking pressing the home button.
I cannot comment everywhere yet, so I'm putting this solution of a similar problem as an answer
After much digging, found out the cause of the problem. Apparently
it's not a bug, it is a feature which does not allow Services or
BroadcastReceivers to launch activities for up to 5 seconds after home
button is pressed. No easy way to overcome this.
More info here:
https://code.google.com/p/android/issues/detail?id=4536
I replaced the activity with a Window added to the window manager of
the running service. This does not cause any delay.
Source link Stackoverflow
First thing we cannot update any UI related stuff in service, neither calling activity nor updating any UI elements,
Same problem i too have faced.
Then i have used EventBus library to communicate UI elements from service
Below is the sample example
public class SendSPLocationService extends Service {
Handler mHandler = new Handler();
Thread downloadThread;
boolean isRunning = true;
private VolleyHelper volleyHelper;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
volleyHelper = new VolleyHelper(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d("run: ", "service is running!");
try {
EventBus.getDefault().post(new FutureJobEvent(false, error.networkResponse.statusCode, errorJson.getString("message")));
} catch (JSONException e) {
e.printStackTrace();
}
// t.cancel();
Log.d("run: ", "service is stopped!");
}
}, 0, 5000);
return START_STICKY;
}
}
Use below code for triggered event to observe..either in activity/fragment
#Override
public void onStart() {
super.onStart();
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
if (EventBus.getDefault().isRegistered(this))
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(TrackSPEvent event) {
if (event.success) {
startActivity(new Intent(this,MainActivity.class));
}
}
I tested with the PendingIntent approach and couldn't find anything wrong. That seems to be working fine. However, for reference, here is what I tried at my end:
public class MyService extends Service {
public static final String SERVICE_COMMAND = "COMMAND";
public static final String TAG = "MyService";
public static final int SERVICE_START = 0x01;
public static final int START_ACTIVITY = 0x02;
private class ServiceHandler extends Handler {
public ServiceHandler(HandlerThread thread) {
super(thread.getLooper());
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case START_ACTIVITY:
Intent ActivityIntent = new Intent(getApplicationContext(), TestActivity.class);
ActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, ActivityIntent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
Log.e(TAG, "Service started activity -> " + System.currentTimeMillis());
default:
break;
}
super.handleMessage(msg);
}
}
private HandlerThread mThread;
private ServiceHandler mHandler;
public MyService() {
mThread = new HandlerThread("ServiceThread");
mThread.start();
mHandler = new ServiceHandler(mThread);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int id = intent.getIntExtra(SERVICE_COMMAND, SERVICE_START);
switch (id) {
case START_ACTIVITY:
Log.e(TAG, "onStartCommand Service -> " + System.currentTimeMillis());
mHandler.sendEmptyMessage(START_ACTIVITY);
break;
default:
break;
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Activity Code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Main";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate main activity -> " + System.currentTimeMillis());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
Log.e(TAG, "onPause main activity -> " + System.currentTimeMillis());
Intent intent = new Intent(this, MyService.class);
intent.putExtra(MyService.SERVICE_COMMAND, MyService.START_ACTIVITY);
startService(intent);
}
}
You can try the same code at your end. May be it can help.
i have used the android:stopWithTask="false" but it never work with one of my services
<service android:name=".EcaService"
android:enabled="true"
android:stopWithTask="false"/>
and the service is:
package com.example.ayham.usefullalarm;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;
/**
* Created by ayham on 7/8/2017.
*/
public class EcaService extends Service {
private BroadcastReceiver batteryReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerBatteryReceiver();
}
private void registerBatteryReceiver() {
batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (MainView.eca_activeCode < 1) {
// How are we charging?
Log.e("in first if", ": done");
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean wirelessCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (acCharge || wirelessCharge) {
Log.e("in second if", ": done");
Intent do_Alarm = new Intent(context, BatteryAlarmView.class);
do_Alarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainView.eca_activeCode++;
context.startActivity(do_Alarm);
}
}
}
};
IntentFilter electricalAIntent = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, electricalAIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("in the receiver","yay");
/*Intent doAlarm = new Intent(this, BatteryAlarmView.class);
doAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(doAlarm);*/
return START_NOT_STICKY;
}
}
in the MainView the code is:
public class MainView extends Activity {
static int eca_activeCode = 0;
Button eca;
Intent eca_intent;
boolean eca_s;
/*#Override
public void onBackPressed() {
Intent itent = new Intent(this, MainView.class);
startActivity(itent);
}*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_view);
this.context = this;
//to be used in decision of the eca
eca_s = false;
//initialize the eca button
eca = (Button)findViewById(R.id.e_status);
//initialize the textView related to the eca
ecaText = (TextView)findViewById(R.id.EText);
//add a click listener to the eca button to start the electrical alarm
eca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//decide whether to activate or not
String s ;
if(!eca_s) {
eca_activeCode = 0;
eca_s = true;
s = "ON";
eca_intent = new Intent(context,EcaService.class);
context.startService(eca_intent);
}
else {
eca_s =false;
s = "Off";
eca_intent = new Intent(context,EcaService.class);
context.stopService(eca_intent);
}
//set the button text to indicate the status of eca
eca.setText(s);
}
});
//receive the battery alarm intent
if(eca_intent != null) {
Intent b_back = getIntent();
eca_s = false;
String s = "Off";
String class_name = b_back.getExtras().getString("Class");
if (class_name.equalsIgnoreCase("BatteryAlarmView")) {
eca_intent = new Intent(context,EcaService.class);
context.stopService(eca_intent);
eca_activeCode = 0;
//set the button text to indicate the status of eca
eca.setText(s);
}
}
}
}
what is wrong with the code, it did not give any error!!
please explain me how does android call lock screen after closing emergency dialer. I've tried to check every second if emergency call is the top activity if it's not then i just lock device but this didn't do it's job in android 5.0 and higher. So, I need another solution.
My code:
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(1/100);
private Thread t = null;
private Context ctx = null;
private boolean running = false;
public MyService2() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
running = true;
ctx = this;
Log.i("Point","PreRun");
t = new Thread(new Runnable() {
#Override
public void run() {
Log.i("Point","preloop");
do {
Log.i("Point", "Prechech");
if (activityManager.getRunningTasks(1).get(0).topActivity.getPackageName().equals("com.android.phone") || activityManager.getRunningTasks(1).get(0).topActivity.getPackageName().equals("com.android.dialer"))
{
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
Log.i("Point", "Thread interrupted: 'KioskService'");
}
} else {
running=false;
Log.i("Task is",activityManager.getRunningTasks(1).get(0).topActivity.getPackageName());
stopSelf();
}
}while (running) ;
}
});
t.start();
Log.i("Point","Done");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("Point","Service is stopped");
}
}
And this:
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.android.phone.EmergencyDialer.DIAL");
startActivity(intent);
Intent intent1 = new Intent(MyActivity.this,MyService2.class);
startService(intent1);
}
});
}
}
You can launch your emergency dialer like this:
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.phone/.EmergencyDialer"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Moreover please check if you have declared your service properly in manifest.
<service
android:name=".MyService2">
</service>
I have an application A which calls the Activity of another application B using the following code.
int request_code = 4;
Intent i = new Intent();
i.setClassName("name.of,packageB","class.name.of.packageB");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(i, request_code);
Target activity in Application B is started and this Target Activity spawn out another service.
I need to return the result to the calling activity once this service finishes.
Is there any way to do this other than calling sendBroadcast(Intent)
I have the following code which is not working. Any help on this is appreciated.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_activity_main);
String finish_activity="";
try{
Intent intent = getIntent();
if(intent!=null && intent.getExtras()!=null)
finish_activity = intent.getExtras().getString("finish_activity", "");
}catch(Exception e){
System.out.println(e.toString());
}
if(finish_activity.equals("")){
Intent intent = new Intent(this, Service.class);
intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startService(intent);
} else{
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
Intent i = new Intent();
setResult(RESULT_OK,i);
finish();
}
}
I am calling this Activity again through the service to return the result which is not working.
Code of service calling my Target Activity.
Intent intent_finish = new Intent(context, TargetActivityName.class);
intent_finish.putExtra("finish_activity", "true");
intent_finish.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent_finish.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
intent_finish.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent_finish);
I am not receiving any callback for the startActivityForResult in my Application A. Any help on this is highly appreciated.
Full code of my two application.
Application A
public class AppA extends Activity {
private Button mOnBootBtn;
private Button mSettingsBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if((requestCode == 4 )&& (resultCode==RESULT_OK)){
System.out.println("result code = "+requestCode);
}
};
public void simulate(View view){
if(view.getId() == R.id.invoke){
int request_code = 4;
Intent i = new Intent();
i.setClassName("com.example.AppB","com.example.AppB.Test");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(i, request_code);
}
}
#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);
}
}
Application B - Test.java
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_activity_main);
String finish_activity="";
try{
Intent intent = getIntent();
if(intent!=null && intent.getExtras()!=null)
finish_activity = intent.getExtras().getString("finish_activity", "");
}catch(Exception e){
System.out.println(e.toString());
}
if(finish_activity.equals("")){
Intent intent = new Intent(this, Service.class);
intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startService(intent);
} else{
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
Intent i = new Intent();
setResult(RESULT_OK,i);
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}
}
Application B- Service.java
public class Service extends Service {
public static Context context;
public static Intent receivedIntent;
public static String calling_intent;
#Override
public void onStart(Intent intent1, int startId) {
// TODO Auto-generated method stub
super.onStart(intent1, startId);
System.out.println("Inside Service");
if (NetworkAvailable(context)) {
Intent intent_finish = new Intent(context, Test.class);
intent_finish.putExtra("finish_activity", "true");
intent_finish.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent_finish.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
intent_finish.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent_finish);
}
}else{
System.out.println("Inside service - No net");
}
}
#Override
public IBinder onBind(Intent receivedIntent) {
// TODO Auto-generated method stub
return null;
}
private static boolean NetworkAvailable(Context context) {
ConnectivityManager connectivityManager;
try{
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}catch(Exception e){
System.out.println(e.toString());
return false;
}
}
}
Thanks in Advance.
I'm a little surprised that your compiler isn't complaining about that extra semi-colon. But you are missing your #Override on your method. Your entire method signature should look like:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if((requestCode == 4 )&& (resultCode==RESULT_OK)){
System.out.println("result code = "+requestCode);
}
}
Intent.FLAG_ACTIVITY_NEW_TASK prevents the caller from receiving results.
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().