Hi boys,
I'm a novice android programmer.
I want to create an app that start when the boot of the phone is complete.
I've write this code, the application work if I click on the icon, but it don't work when the boot of the phone is complete!!
this is my code:
Code:
public class HelloMyBoss extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private String sayd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sayd="";
tts= new TextToSpeech(this, this);
}
@Override
protected void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS) {
// Set preferred language
int result = tts.setLanguage(Locale.ITALY);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Lanuage data is missing or the language is not supported.
Log.e(TAG, "Language is not available.");
} else {
sayHello();
}
} else {
// Initialization failed.
/Log.e(TAG, "Could not initialize TextToSpeech.");
}
}
private void sayHello() {
String hello = "Buon Giorno! Mi sono appena acceso...";
tts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
}
Code:
public class MyIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent arg1) {
Intent startupBootIntent = new Intent(context, HelloMyBoss.class);
startupBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupBootIntent);
}
}
...and this is my manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mrbrown.android.hellomyboss"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloMyBoss"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="4"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Why it don't work?? What's my error???
Help me please!!
Im trying to make a restart app for android for a senior class project but im having some trouble with the code. Anyone have tips or can help me out that would be great. I could message the code if they want.
look into something like this:
Code:
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
Nvm you probably don't need the extras. You might so give it a try with and without
From something awesome
So would that go in the onCreate method?
Sent from my ADR6300 using XDA App
MrAwesomeMan said:
So would that go in the onCreate method?
Sent from my ADR6300 using XDA App
Click to expand...
Click to collapse
if you want your phone to reboot the second you start your app... then yes
i had that code in the onCreate method and i kept getting a force close error. So then i tried this:
Code:
[COLOR="Blue"]public class restart extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void boom(){
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
}
public void myClickHandler(View view) {
boom();
}[/COLOR]
}
and when i click the button it doesnt do anything
here is the main.xml :
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Restart" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
[/COLOR]
and here is the manifest
Code:
[COLOR="Blue"]<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="restart.android"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".restart"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<permission android:name="android.permission.DEVICE_POWER"/>
<uses-permission android:name="android.permission.DEVICE_POWER" />
<permission android:name="android.permission.REBOOT"/>
<uses-permission android:name="android.permission.REBOOT"/>
</manifest>[/COLOR]
Cause you never attached an onClickListener to your button. When i take a break in 15mins ill write an example
From something awesome
Code:
public class restart extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get an instance of that button to be used in the code
Button rebootButton = (Button)findViewById(R.id.button1);
//attach an action to the button
rebootButton.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
boom();
}
});
}
public void boom() {
Intent reboot = new Intent(Intent.ACTION_REBOOT);
reboot.putExtra("nowait", 1);
reboot.putExtra("interval", 1);
reboot.putExtra("window", 0);
sendBroadcast(reboot);
}
}
whether boom() will work or not im not sure. but it will be called when you press the button.
-------------------
public static final String ACTION_REBOOT
Since: API Level 1
Broadcast Action: Have the device reboot. This is only for use by system code.
This is a protected intent that can only be sent by the system.
Constant Value: "android.intent.action.REBOOT"
killersnowman said:
public static final String ACTION_REBOOT
Since: API Level 1
Broadcast Action: Have the device reboot. This is only for use by system code.
This is a protected intent that can only be sent by the system.
Constant Value: "android.intent.action.REBOOT"
Click to expand...
Click to collapse
Well you can use, root + terminal commands.
http://stackoverflow.com/questions/4580254/android-2-2-reboot-device-programmatically
Code:
try {
Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("reboot");
} catch (IOException e) {
}
(Note: there is no error checking or anything special).
The first command will ask for superuser permission. The second, will reboot the phone. There is no need for extra permissions in the manifest file since the actual rebooting is handled by the executed comamand, not the app.
So i tried your code but boom() didnt work so i commented out the button instances in onCreate and put what was in boom() into onCreate but i still kept getting a window asking to force close. i also tried the try and catch loop in boom and in on create and they didnt work either.
Boom() wont work with out being signed as a system app, which would require you t compile your own rom. Try the superuser method above. You will need root
From something awesome
is there a way to shutdown the phone with a intent broadcast?
i was trying to use ACTION_SHUTDOWN instead of ACTION_REBOOT but it didnt works
thx for reply
##### EDIT
problem solved: need to put "ACTION_REQUEST_SHUTDOWN" to the Intent.
I'm a newbie here, so if you think anything is wrong with this post, feel free to point it out. I'm happy to learn.
I hope it's alright to piggyback on this thread, since half of it (the half of it that doesn't deal with using the linux-way of rebooting) actually deals with the same problem, even though it stems from an entirely different source.
In my case it's about sending a ACTION_PACKAGE_ADDED Intent... what's important is that it's protected the same way:
ActivityManagerService.java: broadcastIntentLocked
Code:
if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
|| callingUid == Process.SHELL_UID || callingUid == 0) {
// Always okay.
} else if (callerApp == null || !callerApp.persistent) {
So, it's about satisfying these requirements somehow, or getting around it by sending the broadcast directly.
As you say, you're supposed to sign applications with the same key as the applications in one of these groups to be able to use a sharedUserId, but that's cumbersome and would prevent the application from running on any device other but my own. It would also make updates a lot more complicated... so circumventing it seems the better idea. After all: I am root, so we're already way past any security considerations.
The first thing I've tried is modifying packages.xml , in the hope that the system wouldn't try to re-check the keys. Well, no such luck. From a security standpoint I don't think this check is necessary (if anybody is able to edit packages.xml it's already too late), but Android does it anyway, rebuilding the xml file. Maybe somebody has an idea where and how this re-building could be controlled? Or is it the other way around and the uid originates from somewhere else? It isn't the permission on the APK in /data/app, that's always system:system.
I've also tried starting the APK via "am" hoping that it might inherit the shell uid... it was a desperate attempt and it turned out exactly like anybody would have expected: it didn't work.
The next thing was changing the permission on the process while it's running. On some Linux flavors root can change the permissions in /proc/* , but apparently not on Android.
Then I tried to use ActivityManagerNative::broadcastIntent instead of Content::sendIntent, but the check is buried too deep (as I said before): in order to get past the check I would need access to ActivityManagerService::sendPackageBroadcastLocked , but the object I get through IActivityManager::getDefault is actually only a proxy (ActivityManagerProxy) that forwards the public commands via an IBinder. Naturally the proxy doesn't have the private methods (private methods can still be called, but the proxy is a pretty good isolation layer).
The only thing that I can still think of would be implementing sendPackageBroadcastLocked myself.. it really only depends on the threads, which might be accessible... somehow
Code:
for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--)
mLruProcesses.get(i).thread.dispatchPackageBroadcast(cmd, packages);
These are IApplicationThread objects... they are not implemented in Java... at least the file contains only the prototypes. Is there some way to interact with such objects directly from the shell?
I would be really grateful if anybody had any idea... I just refuse to believe that I'm the first person to need root access rights beyond the shell.
Hi, developers!
I have been googling and searching on stackoverflow a lot, but I still haven't found a solution to my problem:
I'm developing an Android application which uses a BroadcastReceiver to know when the phone is plugged in in order to do some work. On my Nexus 5 running Android 4.4.4 it works as expected, but a friend of mine tested it on his Samsung Galaxy S running Android 2.3.6 Gingerbread and the BroadcastReceiver doesn't work as expected (the onReceive method never gets called).
My code is as follows:
Code:
public class PowerConnectionReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyService.class);
startWakefulService(context, serviceIntent);
}
}
And then I register my BroadcastReceiver in the AndroidManifest:
Code:
<receiver
android:name=".activities.PowerConnectionReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
</intent-filter>
</receiver>
Any ideas on how to make the BroadcastReceiver work?
Thanks in advance.
Well I posted it in android studio forum here but I don't know if it belongs to here..
any way -
READ ONLY EDIT DOWN!!
Okay, so I can't develop nothing as my Android Studio decided to. My all project is full of errors, unknown errors caused by Android Studio.
note: my files are correct, it is an other problem because even if I will import something from google codes it will have errors.
When I import a project everything's fine, but then after indexing and such things, all sudden everything is red and shouldn't be.
My errors for example are :
Code:
button1.setOnLongClickListener(new View.OnLongClickListener() {
....
....
}
Well shouldn't be error but :
Code:
cannot resolve symbol setOnLongClickListener
Another example:
Code:
button1=(Button) findViewById(R.id.button1);
I used this exact code for other button, seems right, I always using this line, it was fine until my Android Studio decided to give me some hard time, this line is full by errors and they are:
Code:
Unknown class: 'button1' , invalid method declaration; return type required, missing method body, or declare abstract
and there are like 20 errors that shouldn't be, things I tried:
1.deleting iml files , .idea folder - worked for a while but now it happened again and it doesn't fix it.
2.reinstalling android studio and then importing project.
3.upgrading android studio version to 1.3
4.restarting my pc.
5.importing project to an other pc, happened after a while.
6.Invalidate caches/ restart.
7.Changing module in project structure - I changed it back to how it was (it didn't help) and I think it caused the manifest error down..
My Module:app build.gradle:
Code:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "firstappdevelopments.david.reactiontime"
minSdkVersion 9
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
}
Also I noticed now, my Manifest file as an error in
Code:
android:name=".MainActivity"
says it has no default structure. something like this. here is the full normal code:
Code:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</manifest>
Please, if someone knows what is the problem or what can I else do, just say, and I am sorry about my English, thank you all.
EDIT!!!:
I deleted this lines:
Code:
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bluetooth = BluetoothAdapter.getDefaultAdapter();
if (bluetooth != null) {
if (bluetooth.isEnabled()) {
bluetooth.startDiscovery();
Set<BluetoothDevice> bondedSet = bluetooth.getBondedDevices();
if(bondedSet.size() > 0){
for(BluetoothDevice device : bondedSet){
newDevicesListView.setVisibility(View.VISIBLE);
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}else{
mArrayAdapter.add("No Devices");
}
}
} else {
textview.setText("bluetooth is disabled, enabling.");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, RESULT_OK);
}
} else{
textview.setText("Bluetooth is not supported.");
}
}
});
AND SUDDENLY ALL THE ERRORS DISSAPPEARED , ANY IDEAS? - The errors was in other lines..
I dont understand the 2nd one but i cann help u in button prblm..
try this
Button button1 = (Button)findViewById(R.id.blahblah);
and button1.setOnLongClickListenetblahblahnla.......
try and let me know
I want to send data from my wear to the phone app.
I've created a phone app with this AndroidManifest.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.car">
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service android:name=".services.ListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<!-- <data android:scheme="wear" android:host="*" android:pathPrefix="/updatecar" /> -->
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my Phone ListenerService:
Code:
package sh.evolutio.car.services;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
public class ListenerService extends WearableListenerService {
private static final String TAG = "ListenerService";
private static final String MESSAGE_PATH = "/updatecar";
@Override
public void onCreate() {
Log.d(TAG, "ListenerService created");
}
@Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d(TAG, "onMessageReceived");
if (messageEvent.getPath().equals(MESSAGE_PATH)) {
Log.d(TAG, "good message");
} else {
Log.d(TAG, "bad message");
}
}
}
my MainActivity with this onCreate:
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startService(new Intent(MainActivity.this, ListenerService.class));
}
When I start the App on my phone I got in the Logcat:
Code:
26131-26131/sh.evolutio.car D/ListenerService: ListenerService created
When I send with the wearapp some data to my phone, my ListenerService didn't fire the onMessageReceived method..
Here is my AndroidManifest from the wearapp:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.carwear">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The MainActivity from the wearapp looks like this:
Code:
package sh.evolutio.carwear;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static String TAG = "MainActivity";
private static final String MESSAGE_PATH = "/updatecar";
Node mNode; // the connected device to send the message to
GoogleApiClient mGoogleApiClient;
private boolean mResolvingError = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Connect the GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
sendMessage("test");
// Enables Always-on
setAmbientEnabled();
}
@Override
protected void onStart() {
super.onStart();
if (!mResolvingError) {
mGoogleApiClient.connect();
}
}
/**
* Resolve the node = the connected device to send the message to
*/
private void resolveNode() {
Log.d(TAG, "resolveNode");
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient)
.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
@Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
Log.d(TAG, "resolvedNode: " + node);
mNode = node;
}
}
});
}
@Override
public void onConnected(Bundle bundle) {
resolveNode();
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "connectionResult: " + connectionResult);
}
/**
* Send message to mobile handheld
*/
private void sendMessage(String Key) {
if (mNode != null && mGoogleApiClient!= null && mGoogleApiClient.isConnected()) {
final String messageKey = Key;
Log.d(TAG, "isConnected: " + mGoogleApiClient.isConnected());
Log.d(TAG, "connected to: " + mNode.getId());
Task<Integer> sendTask = Wearable.getMessageClient(MainActivity.this).sendMessage(mNode.getId(), MESSAGE_PATH, messageKey.getBytes());
sendTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.d(TAG, "onSuccess: " + integer);
}
});
sendTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Wearable.MessageApi.sendMessage(mGoogleApiClient, mNode.getId(), MESSAGE_PATH, messageKey.getBytes()).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
@Override
public void onResult(@NonNull MessageApi.SendMessageResult sendMessageResult) {
if (sendMessageResult.getStatus().isSuccess()) {
Log.v(TAG, "Message: { " + messageKey + " } sent to: " + mNode.getDisplayName());
} else {
// Log an error
Log.v(TAG, "ERROR: failed to send Message");
}
}
}
);
}
}
}
When I the message got send, i got this in the logcat from the wearapp:
Code:
sh.evolutio.carwear D/MainActivity: isConnected: true
sh.evolutio.carwear D/MainActivity: connected to: 778d0d53
sh.evolutio.carwear V/MainActivity: Message: { forward } sent to: HUAWEI Mate 10 Pro
sh.evolutio.carwear D/MainActivity: onSuccess: 17282
so the message was sent to my Mate 10 Pro. But why my Mate 10 Pro App can't receive the Message?