Skip to content
Search

Android.app.Activity

lastmod 2018-08-17created 2015-11-025 edits

Notes on how to use Android's android.app.Activity class.

Methods

getLauncherLargeIconDensity

Returns the density to use.

Simple example

To launch a new activity from an activity, use the following. (The NewActivity class must be written separately)

final Intent kIntent = new Intent(this, NewActivity.class);
startActivity(kIntent);

Then you must register the activity in AndroidManifest.xml as follows.

<manifest>
  <application>
    ...
    <activity android:name="NewActivity"></activity>
    ...
  </application>
</manifest>

When finished, close the activity as follows.

finish();

Unlocking the lock screen from an activity

Add the code below inside the onCreate() method of the activity that should dismiss the lock screen.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

How to get the top Activity

To get the currently running top screen (Top Activity), do the following.

import android.content.Context;
import android.app.ActivityManager;
import java.util.List;
// ... 
ActivityManager mActivityManager = null;
mActivityManager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> rt = mActivityManager.getRunningTasks(1);
String runningTask = rt.get(0).topActivity.toString();

You must also add the following permission.

<uses-permission android:name="android.permission.GET_TASKS" />

startActivityForResult / onActivityResult

Lets activities send and receive information between each other.

  1. Normally the startActivity() method is used to launch an activity, but in this case you must use the startActivityForResult() method.
  2. Run setResult(RESULT_OK, intent); to pass the result along; when you only want to send back a signal that something was done without a result, run setResult(RESULT_OK).
  3. The original activity (the one that called startActivityForResult()) overrides the onActivityResult() method and implements whatever it wants to do with the result it received.

Caveats when using from a Fragment

Occasionally, if the requestCode value in onActivityResult() shows an unexpected value such as 65627, check whether startActivityForResult() was called properly from that Activity. This mistake can occur when using a Fragment; call it with getActivity().startActivityForResult() instead of this.startActivityForResult().

See also

Favorite site

References


  1. Android_startActivityForResult_onActivityResult.pdf ↩