How to open browser in android app? - java

i'm doing a project where i have to call a browser via my android app, but when i call it, the app stops.
the code can be found here: https://github.com/coppetti/android-pulsometer
but for fast view, i have a "Pulsometro" class where
public void onPreviewFrame(byte[] data, Camera cam) {
...
Browser browser = new Browser();
browser.callBrowser(beats);
return;
...
}
and a Browser class where:
public class Browser extends Activity{
public void callBrowser(int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return;
}
}
There's a way to call a browser and my app doesn't breaks?

Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onOpenWebBrowser(View v)
{
Intent webPageIntent = new Intent(Intent.ACTION_VIEW);
webPageIntent.setData(Uri.parse("https://www.google.co.in/"));
try {
startActivity(webPageIntent);
} catch (ActivityNotFoundException ex) {
}
}

Do not just randomly choose superclasses. Do not just create some subclass of Activity and expect it to work.
Move your callBrowser() method into some real Activity implementation, and get rid of Browser entirely.
Or, remove the superclass from Browser, have callBrowser() take a Context as a parameter, and call startActivity() on that Context.

Try this class. Call the callBrowser method and give it and Activity for the context parameter.
public class Browser{
public void callBrowser(Context context, int beats){
String url = "http://www.higia.info/?q="+beats;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}

Related

I need to close current Intent by Pressing Back and turn to my app

I have an Unity app, that has Android plugin that can launch other applications that installed on my smartphone. Here My Java class:
public class LaunchOtherApp extends Activity
{
public static Activity mainActivity;
protected static final String LOGTAG = "MyApp";
private Activity currentActivity;
private Intent i;
private static final LaunchOtherApp ourInstance = new LaunchOtherApp();
public static LaunchOtherApp getInstance() {
return ourInstance;
}
public LaunchOtherApp(){
Log.i(LOGTAG,"Created LaunchOtherApp");
}
public void Launch( final String pack)
{
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setPackage(pack);
currentActivity = UnityPlayer.currentActivity;
Context context = currentActivity.getApplicationContext();
PackageManager pm = context.getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
if (resolveInfos.size() > 0)
{
try
{
ResolveInfo launchable = resolveInfos.get(0);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
context.startActivity(i);
}
catch (SecurityException e)
{
intent = getPackageManager().getLaunchIntentForPackage(pack);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
}
}
}
});
}
#Override
public void onBackPressed() {
finish();
}
Launch - it is method that starting when I click on button in my Unity app... pack variable - it is variable that my Java method receive, and in this variable instantiate Application id. For Example I launched Youtube from my app, and when I pressing Back on my phone, I want to close Youtube, and back to my Unity app... I think I must use onBackPressed method that start when I press Back, but what I must write in this method?
finish(); doesn't help me(( Please, help... Thank you in advance!
Actually, YouTube app is a separate app (might be installed) and you cannot modify that app's behavior. On your button press, Launch method is called and assume YouTube app has started. With the intent:
If you use Intent.FLAG_ACTIVITY_NEW_TASK
YouTube app will start in a new task than yours and pressing back will not return to your app.
If you do not use Intent.FLAG_ACTIVITY_NEW_TASK
The new intent (here YouTube) will be launched in the task of calling activity (your app/game) by default and calling activity will go background. So, pressing back will again return to your app/game as you desired. Because back button press always pops from the backstack of the current task.
So, in the try block of your Launch method, removing the following line should help.
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
For more information about task and back stack, here is the official doc.
Edit
I missed that you have used application context. But, you have to launch from your calling activity context, otherwise you must use this flag. So, I have modified your Launch method and put it here, just replace your Launch method with following:
/* Method to launch an app with its package name */
public void Launch( final String pack)
{
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// Using activity context instead of application context
currentActivity = UnityPlayer.currentActivity;
Context context = currentActivity;
PackageManager pm = context.getPackageManager();
// Similar code to launch from package name
Intent intent = pm.getLaunchIntentForPackage(pack);
if (intent == null) {
// The activity cannot be found or the package name cannot be recognized
// Show some message or do something
Toast.makeText(context, "Cannot launch...", Toast.LENGTH_SHORT).show();
} else {
context.startActivity(intent);
}
}
});
}

Broadcast Receiver not receiving

I know this question comes here fairly often, but I've looked through probably 20 stack overflow questions already and haven't been able to find a solution. I'm fairly certain it's something simple I'm doing wrong but I'm pretty new to Android and this assignment is due in 7 hours or so.
Everything works up until the receiver being called. Here's the call, from a service
Intent intent = new Intent(getApplicationContext(), MainActivity.WatchReceiver.class);
intent.putStringArrayListExtra(CHANGEKEY, changedURLs);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
Now here's the receiver, nested inside the main activity
public class WatchReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(null, "broadcast received");
markAsChanged(intent.getStringArrayListExtra(WatchService.CHANGEKEY));
}
}
And the main activity's on start function, where I register the receiver
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
wr = new WatchReceiver();
markedAsChanged = new ArrayList<Integer>();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(wr, new IntentFilter());
Intent intent = new Intent(this, WatchService.class);
sc = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
wb = (WatchService.WatchBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName name) {
wb = null;
}
};
bindService(intent, sc, Context.BIND_AUTO_CREATE);
}
Explicit Intents do not work with registerReceiver(), whether you are calling registerReceiver() on a Context (for system-level broadcasts) or on an instance of LocalBroadcastManager (for local broadcasts).
Instead:
Define an action string (e.g., final String ACTION="com.dellosa.nick.ITS_HUMP_DAY";)
Use that action string when creating the Intent to broadcast (new Intent(ACTION))
Use that action string when creating the IntentFilter (new IntentFilter(ACTION))

Can't run new activity from onPostExecute

I'm having trouble starting my mainActivity after I have gotten a response from a httpUrlConnection.
Here is my onPostExecute method
protected void onPostExecute(String[] result) {
serv.httphelper.handleResults(result);
}
In the method handleResult() im handling the response code. If the response code is 200 i want to run a new method inside my loginActivity class
public void handleResults(String[] result) {
status = result[0].toString();
instructions = result[1].toString();
jsonString = result[2];
Log.d("DEBUG", status);
if (status.equals("200")) {
serv.loginActivity.proceed();
} else if (status.equals("400")) {
serv.loginActivity.loginError();
} else if (status.equals("401")) {
serv.loginActivity.loginError();
}
}
When i try to start a new activity from the proceed() method i get a nullpointerexception
public void proceed(){
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Log.d("TEST", "Proceed success");
}
My service class for anyone wondering:
public class Service {
public static HttpHelper httphelper = new HttpHelper();
public static HttpConnect conn = new HttpConnect();
public static LoginActivity loginActivity = new LoginActivity();
}
And here is my logCat:
Thanks in advance!
Your problem is when you start the activity at the line:
startActivity(new Intent (LoginActivity.this, MainActivity.class));
Well, you creates an intent that tries to get to LoginActivity.this which probably does not exists!
Instead of this, you have to give an instance of a real activity that is currently running.
A solution that I can suggest you is to pass to proceed() the instance of the currently running activity and put it instead of LoginActivity.this.
In case you don't have a current activity, try to put your application's context instead and add it a flag of a new task.

How to create and start a dream service atomatically android

I am trying to start a dream service. Currently, this is my code:
#SuppressLint("NewApi")
public class DreamLockService extends DreamService {
private static final String TAG = "DreamLockService";
public Utility utilObj = new Utility();
//private Button btnExit;
private Button btnlogin;
private EditText lgPass;
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Exit dream upon user touch
setInteractive(true);
// Hide system UI
setFullscreen(true);
// Set the dream layout
setContentView(R.layout.lockservice);
//setClickListener();
Toast.makeText(this, "Lock Service Created", Toast.LENGTH_LONG).show();
}
//Use this for initial setup, such as calling setContentView().
#Override
public void onDreamingStarted() {
super.onDreamingStarted();
// Exit dream upon user touch
setInteractive(true);
// Hide system UI
setFullscreen(true);
// Set the dream layout
setContentView(R.layout.lockservice);
Toast.makeText(this, "Lock Service Created", Toast.LENGTH_LONG).show();
}
//Your dream has started, so you should begin animations or other behaviors here.
public void onDreamingStopped()
{
super.onDreamingStopped();
}
//Use this to stop the things you started in onDreamingStarted().
public void onDetachedFromWindow()
{
super.onDetachedFromWindow();
}
}
I was unable to start the dream service from another activity. This is what I used:
Intent tempLock = new Intent(MainActivity.this, DreamLockService.class);
//DreamLockService test = new DreamLockService();
startService(tempLock);
I don't understand why it didn't work. How can a dream service be started from another activity?
To start a Dream service from our own app, please try this.
IBinder binder = ServiceManager.getService("dreams");
Parcel data = Parcel.obtain();
data.writeInterfaceToken("android.service.dreams.IDreamManager");
Parcel reply = Parcel.obtain();
try {
if (binder != null)
binder.transact(1, data,reply, Binder.FLAG_ONEWAY);
else
Log.e("TAG", "dreams service is not running");
} catch (RemoteException e) {
e.printStackTrace();
}
To use this, your app should be system app and should have dream permissions in the Manifest file and enable dream setting in Settings.
I tried this and it is working.
You can start the currently selected screen saver using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.systemui", "com.android.systemui.Somnambulator");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
Just need to make sure that your dream service is set and enabled.
Did you include it in your manifest and have an <intent-filter> that matches your action?
If it's ok, then try with:
startService(new Intent(this, DreamLockService.class));
An excellent Services tutorial: http://www.vogella.com/articles/AndroidServices/article.html#scheduleservice_startauto
UPDATE:
As it seems you are not sure if your service is running, you can use this solution found here:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

Calling another activity from AsyncTask

I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .
Here:
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
and Here:
RequestJsonString.this.startActivity(intent);
I have read many posts on this on stackoverflow and tried with activity, context and this. But still I'm not getting it right. I think I should be missing something. Any help is appreciated.
public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
// Code HTTP Get Request and get JSONObject
return jsonObject;
}
protected void onPostExecute(JSONObject jsonObj){
try {
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
RequestJsonString.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("Json_OutPut","Done");
}
}
To start the activity from AsyncTask.
Intent intent = new Intent(YourActivityName.this,DisplayResults.class);
or you can do same like below.
Declare the context instance variable and initialize it in onCreate method.
private Context context;
public void onCreate(Bundle bundle) {
............
context = this;
........
}
Start the activity like this.
Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);
In your case you are referring to asynctask class context
Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
Use a Activity Context
Intent intent = new Intent(ActivityName.this,DisplayResults.class);
Check the link to know when to use getApplicationContext() and when to use Activity Context
When to call activity context OR application context?
Edit:
Pass the Activity context to the asynctask constructor
new RequestJsonString(ActivityName.this).execute(params..);
In your asynctask constructor
Context c;
public RequestJsonString( Context context)
{
c= context;
}
Then
Intent intent = new Intent(c,DisplayResults.class);
startActivity(intent);

Categories

Resources