Streaming live camera feed in app using android studio - java

I'm creating an app that I want to stream my foscam live feed in. I'm pretty new to coding and some of this code is over my head. I found some help getting this far but now am hitting a snag. The app runs but only displays a black screen. I believe i have the manifest and XML code all correct. The problem lies in my code. I hope someone can help me out
package com.rednak.camerastream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity
implements MediaPlayer.OnPreparedListener,
SurfaceHolder.Callback {
final static String USERNAME = "guest";
final static String PASSWORD = "Guest";
final static String RTSP_URL = "rtsp://http://rednak71.ddns.net:8090/live1.sdp";
private MediaPlayer _mediaPlayer;
private SurfaceHolder _surfaceHolder;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up a full-screen black window.
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = getWindow();
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setBackgroundDrawableResource(android.R.color.black);
setContentView(R.layout.activity_main);
// Configure the view that renders live video.
SurfaceView surfaceView =
(SurfaceView) findViewById(R.id.surfaceView);
_surfaceHolder = surfaceView.getHolder();
_surfaceHolder.addCallback(this);
_surfaceHolder.setFixedSize(320, 240);
}
// More to come…
/*
SurfaceHolder.Callback
*/
#
Override
public void surfaceChanged(
SurfaceHolder sh, int f, int w, int h) {}
#
Override
public void surfaceCreated(SurfaceHolder sh) {
_mediaPlayer = new MediaPlayer();
_mediaPlayer.setDisplay(_surfaceHolder);
Context context = getApplicationContext();
Map headers = getRtspHeaders();
Uri source = Uri.parse(RTSP_URL);
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
}
#
Override
public void surfaceDestroyed(SurfaceHolder sh) {
_mediaPlayer.release();
}
private Map getRtspHeaders() {
Map headers = new HashMap();
String basicAuthValue = getBasicAuthValue(USERNAME, PASSWORD);
headers.put("Authorization", basicAuthValue);
return headers;
}
private String getBasicAuthValue(String usr, String pwd) {
String credentials = usr + ":" + pwd;
int flags = Base64.URL_SAFE | Base64.NO_WRAP;
byte[] bytes = credentials.getBytes();
return "Basic" + Base64.encodeToString(bytes, flags);
}
/*
MediaPlayer.OnPreparedListener
*/
#
Override
public void onPrepared(MediaPlayer mp) {
_mediaPlayer.start();
}
}

Make sure that Android's MediaPlayer can actually open and decode your stream. Right now, if the MediaPlayer cannot handle your stream, you are catching any exception and silently ignoring it:
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
At the very least you should log the error:
} catch (Exception e) {
Log.e("MyApp", "Could not open data source", e);
}
Although the MediaPlayer service will most likely pepper the log with its own errors. So what you should do is review the logcat for any messages from the "VideoDecoder" or similar.
To see the logcat in Android Studio, open the "Android Monitor" tab which is on the bottom by default. If you want to see the unfiltered logcat make sure that in the top-right corner of the Android Monitor view it says "No Filters" instead of "Show only selected application".

I have some new code that links to the Foscam videostream but only grabs the frame when it starts then does not stream. Im closer but still need help. Am i on the right track here?
package com.rednak.camstream;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.VideoView;
public class MainCamActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cam);
VideoView vidView = (VideoView)findViewById(R.id.CamVideoView);
String vidAddress = "http://rednak71.ddns.net:8090/CGIProxy.fcgi? cmd=snapPicture2&usr=guest&pwd=guest&t=";
Uri vidUri = Uri.parse(vidAddress);
vidView.setVideoURI(vidUri);
vidView.start();
}
}

Related

Why my implementation of the Dropbox API in Android Studio doesn't work?

I have written this code in Android Studio but as soon as I launch the app it crashes.
package PACKAGE_NAME;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.dropbox.core.DbxException;
import com.dropbox.core.DbxRequestConfig;
import com.dropbox.core.v2.DbxClientV2;
public class MainActivity extends AppCompatActivity {
private static final String ACCESS_TOKEN = MY_ACCESS_TOKEN;
DbxRequestConfig config = DbxRequestConfig.newBuilder("db").build();
DbxClientV2 client = new DbxClientV2(config, ACCESS_TOKEN);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
((TextView)findViewById(R.id.textView)).setText(client.users().getCurrentAccount().getName().getDisplayName());
} catch (DbxException e) {
e.printStackTrace();
}
}
}
I would like to connect to my Dropbox account via access token, I did a similar thing in python and it actually worked.
Someone who knows why this happens?

Camera Permission doesn't work at run time

I am working on QR code scanner App which takes user credentials and scan QR code and store User credentials with the content on QR code.
Since, I am beginner on working with Android App Development and hence, facing several issues such as:
(i) While opening camera permissions in App, it doesn't start automatically.I need to restart the app to open the camera to start QR code scanning.
Is there any possibility through which my app opens camera without taking permission from user. I have seen many apps doing so.
Or is there any modifications I can do to my QR scanner Java file so my camera works on runtime permission :qrscan.java
package com.example.android.loginapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.android.loginapp.R;
import com.google.android.gms.common.wrappers.PackageManagerWrapper;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class qrscan extends AppCompatActivity {
private Button takePictureButton;
SurfaceView surfaceView;
CameraSource cameraSource;
TextView textView;
BarcodeDetector barcodeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.qrcode);
super.onCreate(savedInstanceState);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
textView=(TextView)findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this,barcodeDetector).setRequestedPreviewSize(640,480).build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(qrscan.this, new String[] {Manifest.permission.CAMERA}, 0);
return;
}
try {
cameraSource.start(holder);
}catch(IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()!=0){
textView.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator=(Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textView.setText(qrCodes.valueAt(0).displayValue);
}
});
}
}
});
}
}
(ii) My second issue is that: I want to store credentials of user with the QR code. But I lack knowledge of database and all those stuff.
Is there any easy way through which I can store such data ?
Something like storing data on google cloud.
I have already seen similar questions on stack overflow but none of them solves my issue.
This question is similar but doesn't help : surface view does not show camera after i gave permission
You need to check for permission to camera in activity where you have qr reader functionality before you start using it. If application do not have permission to that device you push it for ask again or just ignore it and let user know about it by message.
Example code
private void permissionAsk(String permission){
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
String permission = Manifest.permission.CAMERA;
permissionAsk(permission);
permissionAsk(Manifest.permission.RECORD_AUDIO);
permissionAsk(Manifest.permission.WRITE_EXTERNAL_STORAGE);
You can easly find more solutions like that almost ready to go.

Android Get Shared Preferences of Another application

I'm trying to get some data from Word Readable Shared Preferences of another application.
I'm sure that other application Shared Preferences is World Readable and name is present.
But I'm retrieving empty string.
Here is my code:
package com.example.sharedpref;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.SharedPreferences;
public class MainActivity extends AppCompatActivity {
private TextView appContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContent = (TextView) findViewById(R.id.test1);
appContent.setText("Test Application\n");
appContent.setText(getName(this));
}
protected String getName(Context context){
Context packageContext = null;
try {
packageContext = context.createPackageContext("com.application", CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = packageContext.getSharedPreferences("name_conf", 0);
String name = sharedPreferences.getString("name", "");
return name; //HERE IS WHERE I PUT BREAKPOINT
}
catch (PackageManager.NameNotFoundException e) {
return null;
}
}
}
Here is some debug I retrieve from debug mode:
and piece of code from the app that I'm trying to access shared preferences:
/* access modifiers changed from: protected */
#SuppressLint({"WorldReadableFiles"})
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_welcome);
Editor edit = getApplicationContext().getSharedPreferences("name_conf", 0).edit();
edit.putBoolean("FIRSTRUN", false);
edit.putString("name", "Eddie");
edit.commit();
new DBHelper(this).getReadableDatabase();
PS. I Cant edit code of second app im trying access to!
Something im missing?
You can not edit it from another apps,
if you want, you can use FileWriter to create a txt file and use it in other apps

The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (startingpoint)

I am trying to develop a twitter client using android. My entire code is error free for now excepting the line " signIn.setOnClickListener(this);". I've tried following every other suggestion but they don't seem to help. The error reported is "The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (startingpoint)". According to suggestions it seems i should use "View" instead of "signIn". What could be the possible explanation and where do i need to correct my code?
package com.HIT.bjak;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class startingpoint extends Activity implements OnClickListener {
/** developer account key for this app */
public final static String TWIT_KEY = "xxx";
/** developer secret for the app */
public final static String TWIT_SECRET = "xxx";
/** app url */
public final static String TWIT_URL = "bjak-android:///";
/** Twitter instance */
private Twitter bjak_instance;
/** request token for accessing user account */
private RequestToken bjak_RequestToken;
/** shared preferences to store user details */
private SharedPreferences Prefs;
// for error logging
private String LOG_TAG = "startingpoint";
Button signIn;
String oaVerifier=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// get the preferences for the app
bjak_instance = (Twitter) getSharedPreferences("TweetPrefs", 0);
// find out if the user preferences are set
if ( Prefs.getString("user_token", null) == null) {
// no user preferences so prompt to sign in
setContentView(R.layout.main);
// get a twitter instance for authentication
bjak_instance = new TwitterFactory().getInstance();
// pass developer key and secret
bjak_instance.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
// try to get request token
try {
// get authentication request token
bjak_RequestToken = bjak_instance.getOAuthRequestToken(TWIT_URL);
} catch (TwitterException te) {
Log.e(LOG_TAG, "TE " + te.getMessage());
}
// setup button for click listener
signIn = (Button)findViewById(R.id.signin);
signIn.setOnClickListener(this);
//attempt to retrieve access token
try
{
//try to get an access token using the returned data from the verification page
AccessToken accToken = bjak_instance.getOAuthAccessToken(bjak_RequestToken, oaVerifier);
//add the token and secret to shared prefs for future reference
Prefs.edit()
.putString("user_token", accToken.getToken())
.putString("user_secret", accToken.getTokenSecret())
.commit();
//display the timeline
setupTimeline();
}
catch (TwitterException te)
{ Log.e(LOG_TAG, "Failed to get access token: " + te.getMessage()); }
} else {
// user preferences are set - get timeline
setupTimeline();
}
}
/**
* Click listener handles sign in and tweet button presses
*/
public void onClick(View v) {
// find view
switch (v.getId()) {
// sign in button pressed
case R.id.signin:
// take user to twitter authentication web page to allow app access
// to their twitter account
String authURL = bjak_RequestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL)));
break;
// other listeners here
default:
break;
}
}
/*
* onNewIntent fires when user returns from Twitter authentication Web page
*/
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//get the retrieved data
Uri twitURI = intent.getData();
//make sure the url is correct
if(twitURI!=null && twitURI.toString().startsWith(TWIT_URL))
{
//is verifcation - get the returned data
oaVerifier = twitURI.getQueryParameter("oauth_verifier");
}
}
private void setupTimeline() {
Log.v(LOG_TAG, "setting up timeline");
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}`
this is because the interface your activity implements is wrong!
import android.content.DialogInterface.OnClickListener;
...
public class startingpoint extends Activity implements OnClickListener {
you should implements this interface View.OnClickListener.

Android bugs on device. What should I do to fix them? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html

Categories