I'm trying to make facebook for "someone" else opens on application, not on a browser, for example National Geography https://www.facebook.com/natgeo
Here is the code I have:
ddc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/natgeo"));
startActivity(browserIntent);
}
});
I found one on stackoverflow and I tried it and it has errors, here is the code:
try {
//try to open page in facebook native app.
String uri = "fb://page/" + natgeo; //Custom URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
catch (ActivityNotFoundException ex){
//facebook native app isn't available, use browser.
String uri = "https://www.facebook.com/natgeo" + natgeo; //Normal URL
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uriMobile));
startActivity(i);
}
the thing is I want, if someone didn't have facebook App, it will open in the browser.
Edited
package fa;
import com.f.fa.R;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button ddc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
addListenerOnButton();
}
public void addListenerOnButton() {
ddc = (Button) findViewById(R.id.ddc);
try {
//try to open page in facebook native app.
String uri = "fb://page/" + natgeo; //Custom URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
catch (ActivityNotFoundException ex){
//facebook native app isn't available, use browser.
String uri = "https://www.facebook.com/natgeo" + natgeo; //Normal URL
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(i);
}
}
}
You use a variable, which is not declared before (read compiler errors)..
Add String natgeo = "my content"; before your try-catch block to make your code compiling.
Related
I've been able to successfully create an app (thanks davidgyoung!) that monitors beacons in the background and then subsequently opens the app in the background.
Now I would like my app to first prompt with a notification in the status bar saying something like "I've detected a beacon! Would you like to open out app?". Then the user would click on the notification to open the app or dismiss it and ignore the notification.
I've searched on stack overflow for something like but haven't had much success in finding something relevant to beacons. I did find this page that talks about adding StatusBar notifications but I'm not having much success.
Particularly its in my BeaconReferenceApplication.java and MonitoringActivity.java file. I think I put the code in the correct place (after didEnterRegion) but I have unresolved classes for areas like notificationButton, setLatestEventInfo, etc. Can someone help? Thanks in advance!
BeaconReferenceApplication.java:
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.Identifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.RegionBootstrap;
import org.altbeacon.beacon.startup.BootstrapNotifier;
public class BeaconReferenceApplication extends Application implements BootstrapNotifier {
private static final String TAG = "BeaconReferenceApp";
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private MonitoringActivity monitoringActivity = null;
public void onCreate() {
super.onCreate();
BeaconManager beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb. To find the proper
// layout expression for other beacon types, do a web search for "setBeaconLayout"
// including the quotes.
//
beaconManager.getBeaconParsers().clear();
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"));
Log.d(TAG, "setting up background monitoring for beacons and power saving");
// wake up the app when a beacon is seen
Region region = new Region("backgroundRegion", Identifier.parse("2F234454F4911BA9FFA6"), null, null);
regionBootstrap = new RegionBootstrap(this, region);
// simply constructing this class and holding a reference to it in your custom Application
// class will automatically cause the BeaconLibrary to save battery whenever the application
// is not visible. This reduces bluetooth power usage by about 60%
backgroundPowerSaver = new BackgroundPowerSaver(this);
// If you wish to test beacon detection in the Android Emulator, you can use code like this:
// BeaconManager.setBeaconSimulator(new TimedBeaconSimulator() );
// ((TimedBeaconSimulator) BeaconManager.getBeaconSimulator()).createTimedSimulatedBeacons();
}
#Override
public void didEnterRegion(Region arg0) {
// In this example, this class sends a notification to the user whenever a Beacon
// matching a Region (defined above) are first seen.
Log.d(TAG, "did enter region.");
if (!haveDetectedBeaconsSinceBoot) {
Log.d(TAG, "sending notification to StatusBar");
#SuppressWarnings("deprecation")
private void Notify(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.mipmap.ic_launcher,
"New Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MonitoringActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(MonitoringActivity.this, notificationTitle,
notificationMessage, pendingIntent);
notificationManager.notify(9999, notification);
}
}
} else {
if (monitoringActivity != null) {
Log.d(TAG, "auto launching MainActivity");
// The very first time since boot that we detect an beacon, we launch the
// MainActivity
Intent intent = new Intent(this, MonitoringActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Important: make sure to add android:launchMode="singleInstance" in the manifest
// to keep multiple copies of this activity from getting created if the user has
// already manually launched the app.
this.startActivity(intent);
haveDetectedBeaconsSinceBoot = true;
}
}
}
#Override
public void didExitRegion(Region region) {
if (monitoringActivity != null) {
Log.d(TAG,"I no longer see a beacon.");
}
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
if (monitoringActivity != null) {
Log.d(TAG,"I have just switched from seeing/not seeing beacons: " + state);
}
}
private void sendNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle("Beacon Reference Application")
.setContentText("An beacon is nearby.")
.setSmallIcon(R.mipmap.ic_launcher);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(new Intent(this, MonitoringActivity.class));
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
public void setMonitoringActivity(MonitoringActivity activity) {
this.monitoringActivity = activity;
}
}
MonitoringActivity.java:
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import org.altbeacon.beacon.BeaconManager;
public class MonitoringActivity extends Activity {
protected static final String TAG = "MonitoringActivity";
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private WebView mWebView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring);
// code for button notification
Button notificationButton = (Button) findViewById(R.id.notificationButton);
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Notify("Title: Meeting with Business",
"Msg:Pittsburg 10:00 AM EST ");
}
});
// code for button notification
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://communionchapelefca.org/edy-home");
mWebView.setWebViewClient(new MyAppWebViewClient());
verifyBluetooth();
Log.d(TAG, "Application just launched");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect beacons in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#TargetApi(23)
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
}
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
public void onRangingClicked(View view) {
Intent myIntent = new Intent(this, RangingActivity.class);
this.startActivity(myIntent);
}
#Override
public void onResume() {
super.onResume();
((BeaconReferenceApplication) this.getApplicationContext()).setMonitoringActivity(this);
}
#Override
public void onPause() {
super.onPause();
((BeaconReferenceApplication) this.getApplicationContext()).setMonitoringActivity(null);
}
private void verifyBluetooth() {
try {
if (!BeaconManager.getInstanceForApplication(this).checkAvailability()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth not enabled");
builder.setMessage("Please enable bluetooth in settings and restart this application.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
catch (RuntimeException e) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Bluetooth LE not available");
builder.setMessage("Sorry, this device does not support Bluetooth LE.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
finish();
System.exit(0);
}
});
builder.show();
}
}
}
So I was able to fix my problem by using the example from the Android Developers website for Notifications. I used their sample code, adapted it to my use, and then even further used .bigText to make my notification look great. Credit goes to them and daviggyoung for getting my app working. Thanks!
I also didnt need to edit my MonitoringActivity.java like I posted earlier.
final BeaconReferenceApplication.java:
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.Identifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.RegionBootstrap;
import org.altbeacon.beacon.startup.BootstrapNotifier;
public class BeaconReferenceApplication extends Application implements BootstrapNotifier {
private static final String TAG = "BeaconReferenceApp";
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private MonitoringActivity monitoringActivity = null;
public void onCreate() {
super.onCreate();
BeaconManager beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb. To find the proper
// layout expression for other beacon types, do a web search for "setBeaconLayout"
// including the quotes.
//
beaconManager.getBeaconParsers().clear();
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19"));
Log.d(TAG, "setting up background monitoring for beacons and power saving");
// wake up the app when a beacon is seen
Region region = new Region("backgroundRegion", Identifier.parse("2F234454F4911BA9FFA6"), null, null);
regionBootstrap = new RegionBootstrap(this, region);
// simply constructing this class and holding a reference to it in your custom Application
// class will automatically cause the BeaconLibrary to save battery whenever the application
// is not visible. This reduces bluetooth power usage by about 60%
backgroundPowerSaver = new BackgroundPowerSaver(this);
// If you wish to test beacon detection in the Android Emulator, you can use code like this:
// BeaconManager.setBeaconSimulator(new TimedBeaconSimulator() );
// ((TimedBeaconSimulator) BeaconManager.getBeaconSimulator()).createTimedSimulatedBeacons();
}
#Override
public void didEnterRegion(Region arg0) {
// In this example, this class sends a notification to the user whenever a Beacon
// matching a Region (defined above) are first seen.
Log.d(TAG, "did enter region.");
if (!haveDetectedBeaconsSinceBoot) {
Log.d(TAG, "sending notification to StatusBar");
//begin code for notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Message from Communion Chapel")
.setContentText("Welcome! Thanks for coming!")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("We noticed that you're here today, click here to open the app and get today's Sermon Notes and Bulletin."))
.setAutoCancel(true);
;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MonitoringActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MonitoringActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(123, mBuilder.build());
}
}
#Override
public void didExitRegion(Region region) {
if (monitoringActivity != null) {
Log.d(TAG,"I no longer see a beacon.");
}
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
if (monitoringActivity != null) {
Log.d(TAG,"I have just switched from seeing/not seeing beacons: " + state);
}
}
private void sendNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle("Beacon Reference Application")
.setContentText("A beacon is nearby.")
.setSmallIcon(R.drawable.app_icon);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(new Intent(this, MonitoringActivity.class));
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build());
}
public void setMonitoringActivity(MonitoringActivity activity) {
this.monitoringActivity = activity;
}
}
I am working on a app that when you swipe up on the home button the app opens. I have everything else done bet the code to accomplish the open on swipe up on home button part. How do I do this?
Any help would be amazing.
Here's my java code if needed:
package com.d4a.toolbelt;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class QuickLaunch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_launch);
}
/** Called when the user clicks the music button */
public void music(View view) {
Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(intent);
}
/** Called when the user clicks the play button */
public void play(View view) {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.android.vending");
startActivity(launchIntent);
}
/** Called when the user clicks the web button */
public void web(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com/"));
startActivity(browserIntent);
}
/** Called when the user clicks the email button */
public void email(View view) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.email");
startActivity(intent);
}
/** Called when the user clicks the sms button */
public void chat(View view) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.d4a.sms","de.ub0r.android.smsdroid.ConversationListActivity"));
intent.putExtra("grace", "Hi");
startActivity(intent);
}
/** Called when the user clicks the settings button */
public void settings(View view) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.settings");
startActivity(intent);
}
/** Called when the user clicks the camara button */
public void cam(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
/** Called when the user clicks the video camara button */
public void video_cam(View view) {
Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");
startActivityForResult(intent, 0);
}
}
Thanks a million in advance guys!
I figured it out you need this line of code in the manifest:
<intent-filter>
<action android:name="android.intent.action.ASSIST" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
Thanks to home launcher being open source I got my answer I hope this helps out anyone else who is in my shoes
There is a strange behaviour of assigning/modifying instance variable of the class inside Button OnClick() handlers.
As shown below, the instance variable "CurrentFile" is modified inside imgBtn.setOnClickListener() handlers. But when this variable is accessed in onActivityResult() method, this variable contains the value "null".
According to my understanding, the activity "GetPicActivity" will not be destroyed till the Camera activity returns. So, the instance variable "CurrentFile" should not be null.
Please help, if I am missing some basics.
import java.io.File;
import java.io.IOException;
import com.favoritepics.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class GetPicActivity extends Activity {
protected static final int ID_REQ_IMAGE_CAPTURE = 1;
protected static final int ID_REQ_PICK_PHOTO = 0;
protected File currentFile = null; /// Goal is "to modify this variable inside Button onClick handlers"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.DKGRAY));
setContentView(R.layout.activity_get_pic);
// set handler image gallery
ImageButton imgBtn = (ImageButton) findViewById(R.id.imgGallery);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
// create intent to take picture on camera
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, ID_REQ_PICK_PHOTO);
}
});
// set handler for camera image
imgBtn = (ImageButton) findViewById(R.id.imgCamera);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempDir = Environment.getExternalStorageDirectory();
File tempFile = null;
try {
currentFile = File
.createTempFile("_jpeg_", ".jpg", tempDir);
} catch (IOException exception) {
Toast.makeText(
GetPicActivity.this,
"Problem occured during creation of temp file! "
+ exception.getMessage(),
Toast.LENGTH_SHORT).show();
}
if (currentFile != null) {
takePicture.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(currentFile));
startActivityForResult(takePicture, ID_REQ_IMAGE_CAPTURE);
}
}
});
// set handler for cancel button
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ID_REQ_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
Intent newIntent = new Intent();
newIntent.putExtra("TYPE", requestCode);
newIntent.putExtra("PATH", currentFile.getAbsolutePath());
setResult(RESULT_OK, newIntent);
finish();
}
break;
default:
break;
}
}
}
click here to see Logcat messages
Steps what I intend to do:
1, Create a temporary file in External storage for the destination of Camera picture
2, Start Camera to take a picture by passing the URI of temporary file
3, OnActivityResult() from camera, return the (temporary) File path to previous activity for further process
But here what I see is,
As soon as the Camera is started & picture is taken, the GetPicActivity is created again. Because of this, the instance variable "CurrentFile" will be null & in OnActivityResult() , I could not get the File path of temporary file.
Why is the GetPicActivity destroyed after starting Camera?
When the camera is started, the Camera appears in the screen orientation "Landscape".
Even the orientation of already existing activity stack is changed to "Landscape" itseems.
So, When the result of Camera is returned to GetPicActivity method OnActivityResult(), the GetPicActivity is created again. But now, the instance variable "CurrentFile" is null. This, gives a NullPointerException.
i wan currently developing an app for android, but.. There is an activity of mine, in which the user shall click on a button and it would open the Android Terminal EMulator which would have been installed on the user device, but right now, i have an issue, my codes are not working.. check it out
ClockWorkModFlash.java
package com.loadedgeek.myupgrade;
import android.os.Bundle; import android.app.Activity; import
android.os.Handler; import android.content.Intent; import
android.widget.Button; import android.view.View;
public class ClockWorkModFlash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clockworkmod_activate);
Button bClock = (Button) findViewById(R.id.FlashClockWork);
bClock.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager managerclock = getPackageManager();
i = managerclock.getLaunchIntentForPackage(jackpal.androidterm);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
}
});
}}
The Eclipse is not allowing me compile the app, as that is the last activity, it says Packagemanager and OnClickListner could not be resolved... any ideas?
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("application Package name /application launcher activity name"));
intent.addCategory("android.intent.category.LAUNCHER");
startActivity(intent);
PackageManager managerclock = getPackageManager();
Intent i = managerclock.getLaunchIntentForPackage(jackpal.androidterm);
i.addAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
or
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("jackpal.androidterm");
intent.addCategory("android.intent.category.LAUNCHER");
startActivity(intent);
by the way,your error "Packagemanager and OnClickListner could not be resolved", I guess that you can change the code from:
bClock.setOnClickListener(new OnClickListener() {…}
to:
bClock.setOnClickListener(new View.OnClickListener() {…}
I'm trying to develop an app which will scan a barcode, store the value in a variable, then scan another barcode and match that value with the previous value and return a 'match' or 'no match' result. I have already got the first part working thanks to help from foamyguy, here's the initial code that I used,
package com.barcodesample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class BarcodeSample extends Activity {
private Button scanBtn;
private TextView resultsTxt;
/** Called when the activity is first created. */;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
scanBtn = (Button) findViewById(R.id.scanBtn);
resultsTxt = (TextView) findViewById(R.id.resultsTxt);
scanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
resultsTxt.setText("Scanning...");
Intent intent = new intent("com.google.zxing.client.android.SCAN");
try {
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
new AlertDialog.Builder(v.getContext())
.setTitle("WARNING:")
.setMessage("You don't have Barcode Scanner installed. Please install it.")
.setCancelable(false)
.setNeutralButton("Install it now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
})
.show();
}
}
});
}
/*Here is where we come back after the Barcode Scanner is done*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel. If the user presses 'back' before a code is scanned.
resultsTxt.setText("Canceled");
}
}
}
}
Now how do I start another intent with another scan button similar to the one above, and finally how to compare both values and return the match or no match in a new screen?
Thanks in advance for the valuable advice
Use the same code on the other button except following.
startActivityForResult(intent, 1); // right now it's 0 for button 1
Now add one more section in onActivityResult for returning results for 2nd button.
if (requestCode == 1) {
// your code here that will be used for comparing.
}