SDK Android : How to open Shutdown/Reboot dialog for the device - android

I'm new here.
I have a problem, i try to shutdown a 4.2.2 android device (not root).
I know that ACTION_SHUTDOWN not works with unroot device.
So i want to open the existing shutdown/reboot/airplane dialog, the same we get when we maintain the on/off button. Then the user just have to click shutdown button.
I try to create by this way, without result...
Intent intent = new Intent(Settings.ACTION_DISPLAY_SETTINGS); // or others settings
startActivity(intent);
Thanks,

The is no public sdk access to open the power button menu programatically.
This link has all the approches Here.Simulating power button press to display switch off dialog box

InputManager.getInstance().injectInputEvent(new InputEvent(KeyEvent.KEYCODE_POWER, keyCode), sync);
'sync' becomes either of these:
InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT
and you need
import android.hardware.input.InputManager;
This is untested, but puts you in the right direction, also bare in mind, functionality like this is NOT recommend.
failing that:
public static void simulateKey(final int KeyCode) {
new Thread() {
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
}
and simply call it like
simulateKey(KeyEvent.KEYCODE_POWER);

Related

Best practice for closing websocket in android

I am using this library for connecting to a websocket server from android.
Specifically this part :
AsyncHttpClient.getDefaultInstance().websocket("ws://192.168.2.10:8000/temp" , "my-protocol", new WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.send("a string");
webSocket.setStringCallback(new StringCallback() {
#Override
public void onStringAvailable(String s) {
Debug.Log( LOGTAG ,"I got a string: " + s);
}
});
webSocket.close(); // issue here
}
});
I would like to close the socket when I click a button. Now everytime I want to send a message to the socket I open it and close it.
I would like to open it once and keep it alive and close it when I click a close button. My idea was to pass a variable to the WebSocketConnectCallback and make a static variable and based on this variable close the socket.
I would like to know what is the best practice in a situation like this.
Use the Application class (http://developer.android.com/reference/android/app/Application.html):
Inherid your own class for Application and here you can track the socket, open it, close it as you need.
See a tutorial (first google match, maybe there is a better one): http://www.intertech.com/Blog/androids-application-class/
So basically extend Application and add your class in the manifest file as application class.
Your may add a timer that might close the socket after several time while not used.

Injecting key events from android service

I'm making a custom navigation bar for android. I want to inject KEYCODE_BACK event from any part of application whether I'm on menu, home screen or any application. Basically, any part of android. How can I do that using services. I found one piece of code but it doesn't work coz I have to install application as system.
new Thread() { // requires to use INJECT_EVENTS permission in android
#Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
} catch (Exception e) {
Log.e("Exception when sendKeyDownUpSync", e.toString());
}
}
}.start();
For this to work, I use uses-permission android:name="android.permission.INJECT_EVENTS" but it throws error saying INJECTING INTO ANOTHER APPLICATION REQUIRES INJECT_EVENT PERMISSION.
Is there anyway to implement back button through service.
Thanks

programmatically close Android settings after event has occured

So I created an app that connects to a wireless display on Android automatically for the user. The easiest way I found to do that is by opening the Screen Mirroring settings. This makes it easier for the user, so they don't have to go up to settings and enable it themselves.
Now that I have connected to the display, I want the Screen Mirroring screen to go away and return to the app or to the home screen if the user wants.
Here is the code I use to open Screen Mirroring settings to connect the user to the display after he clicks on a button:
try
{
activityint = 1;
Log.d("DEBUG", "open WiFi display settings in HTC");
startActivityForResult(new Intent("com.htc.wifidisplay.CONFIGURE_MODE_NORMAL"),activityint);
} catch (Exception e)
{
try
{
activityint = 2;
Log.d("DEBUG", "open WiFi display settings in Samsung");
startActivityForResult(new Intent("com.samsung.wfd.LAUNCH_WFD_PICKER_DLG"),activityint);
}catch (Exception e2)
{
activityint=3;
Log.d("DEBUG", "open WiFi display settings in stock Android");
startActivityForResult(new Intent("android.settings.WIFI_DISPLAY_SETTINGS"),activityint);
}
}
And then I have a broadcastreceiver that listens for WIFI_P2P_CONNECTION_CHANGED_ACTION. When this happens, it will look to see if we are now connected before launching other things and then attempting to close the settings activity.
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION))
{
/**
* What to do if the P2P connection has changed
*/
try
{
NetworkInfo info = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info!=null && info.isConnected())
{
connected(true);
//Kill the settings activity
finishActivity(activityint);
}else if(info!=null && !info.isConnected())
{
connected(false);
}
}catch(Exception e)
{
Log.e("DEBUG", "exception", e);
}
}
}
The problem is that it kills the settings activity before the connection is finalized. So it will back out of the settings activity and the Screen Mirroring connection will cancel a moment before it connects. Is there a better way or a different way to be able to back out of the Settings activity? Or am I listening for the wrong intent in my receiver?
Thanks
The only way I was able to close a settings page on some event, is to start my activity again with the Intent.FLAG_ACTIVITY_CLEAR_TOP flag.
This way, because your activity is the one that opened the settings activity, the flag will make the system finish it. To the user it will appear that the settings activity just went away.
I guess I'm answering my own questions. I found this code that allows me to send a delayed response. I know this is crummy programming because some devices will finish before others, but this works for me at the moment. If anyone knows of a better way, please feel free to let me know.
This goes in my broadcast receiver's onReceive method.
NetworkInfo info = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info!=null && info.isConnected())
{
connected(true);
new Handler().postDelayed(new Runnable()
{
public void run()
{
finishActivity(activityint);
}
}, 5000);
}else if(info!=null && !info.isConnected())
{
connected(false);
}
EDIT: This actually does not work for me. After testing further, I found that it will kick me back to the home screen after a few moments even when I just open the app. It's pretty annoying. Anyone know of a better idea?

GWT equivalent of an intent

I am just starting off with Google Web Toolkit, coming from programming in Android. Since it's all java(ish) I expected it to be similar. In my app I have an entrypoint where the user will upload an excel file and hit submit. After they hit submit they should be taken to a new page where I will be displaying some information from the excel that they just uploaded.
In Android it would look something like
myAndroidBTN.setOnClickListener (new OnClickListener() {
public void onClick(View v) {
try {
final Intent myIntent = new Intent(this, NextClass.class));
startActivity(myIntent);
} catch (Exception e) { }
}
In the GWT App I have
Button btnSubmit = new Button("Submit");
btnSubmit.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
}
});
Documentation for GWT is doesn't seem to be anywhere near what it is for android so I can't find the right way to open a new java file. How should this be done?
EDIT
Some of you have miss-interpreted my question. I don't want to imply that I can build the equivalent of an android app in a browser with GWT, I just wanted to see the equivalent of an OnClick event taking you to a new page/section.
Look at Activities and Places.
https://developers.google.com/web-toolkit/doc/latest/DevGuideMvpActivitiesAndPlaces

How to make an Android app that depends on another app?

If I create an app that depends on another app or apps (eg: the Facebook and Twitter apps), yet they are not installed, is there a method of checking for those dependencies and installing them at the same time as my own app?
I did this in my application which requires the zxing scanner app to be installed.
You will want this inside your onclick or ontouch:
try{
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
startActivityForResult(intent, 0);
} catch (Exception e) {
createAlert("Barcode Scanner not installed!", "This application uses " +
"the open source barcode scanner by ZXing Team, you need to install " +
"this before you can use this software!", true);
}
which calls
public void createAlert(String title, String message, Boolean button) {
// http://androidideasblog.blogspot.com/2010/02/how-to-add-messagebox-in-android.html
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
if ((button == true)) {
alertDialog.setButton("Download Now",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://search?q=pname:com.google.zxing.client.android"));
startActivity(browserIntent);
}
});
}
alertDialog.show();
}
Then after sorting out all that code out I realise you asked for it to be installed at the same time as your app. Not sure if i should post this code, but it may be helpful
Short answer: No, you cannot automatically install other applications as dependencies.
Longer answer:
Android Market does not let you declare other applications to install as a dependency. As a system, Market appears to be designed for single application installs -- not Linux distro style mega dependency graphs.
At runtime, you can test for installed apps and punt your user over to the Market if so. See the techniques suggested by #QuickNick (testing if an app is installed) and #TerryProbert (punting to market) if that's what you want.
Your best bet is probably to design your app to gracefully degrade if dependencies are not available, and suggest (or insist) that they head over to market to install them.
Start from this:
Intent mediaIntent = new Intent("com.example.intent.action.NAME");
// add needed categories
List<ResolveInfo> listResolveInfo = getPackageManager().queryIntentServices(mediaIntent, 0);
if (listResolveInfo.size() != 0) {
//normal behavior
} else {
//install what you need
}
I give you example of querying services. If you want to check activities, then you will call queryIntentActivities().
I think following the pattern outlined in this post on the Android Developer Blog will help you.
http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
As TerryProbert points out if you know that the Intent is not available prompt the user to install the missing app.
Here's what I use to return the first mission activity that exists:
try {
Class<?> missionClass = Class.forName(mPackageName+".Mission"+mission);
Method missionDescription;
missionDescription = missionClass.getMethod("missionDescription");
mMissionDescription = (String) missionDescription.invoke(null);
if (mMissionDescription.length() > 0) {
nextMission = mission;
break;
}
} catch (Exception e) {
//DEBUG*/Log.v(this.getClass().getName(), "onResume: Mission no "+mission+" not found: "+e.getMessage());
}
Each mission is held in a separate class, derived from a Mission base class. Derived classes are called Mission1, Mission24 etc.
Not all missions are defined.
The base class has an abstract class missionDescription which returns a string describing the mission.
This code is inside a loop so tests mission=1 to 99, trying to call missionDescription. It returns when the Description for the first mission found is returned.

Categories

Resources