new to android programming. I am trying to create a very simple flashlight app in android studio and i want to be able to run the app when the phone is locked and as a background activity. I have understood that i should use Service but i can't figure out how or where to implement it in my code.
Thank you.
MainActivity:
public class MainActivity extends Activity {
//flag to detect flash is on or off
private boolean isLightOn = false;
private Camera camera;
private ImageButton button;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (ImageButton) findViewById(R.id.imageButton);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return;
}
camera = open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isLightOn) {
p.setFlashMode(FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn = false;
button.setImageResource(R.drawable.onbuttontrans);
} else {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
button.setImageResource(R.drawable.offbuttontrans);
isLightOn = true;
}
}
});
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.g131146.flashlight" >
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application android:theme="#android:style/Theme.Black.NoTitleBar"
android:icon="#drawable/appicon">
<activity
android:label="Flashlight"
android:name=".MainActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I was facing this similar issue and solved it through the following method.
Here we basically combined the code in the onPause and onStop methods. Hence you could comment out the code in there. I didn't really use any Service as this fixed the issue. Hope it helps!
Add this in your MainActivity:
#Override
public void onBackPressed() {
super.onBackPressed();
myParameters = myCamera.getParameters();
myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(myParameters);
myCamera.stopPreview();
FlashOn = false;//this is a boolean
if (myCamera != null) {
myCamera.release();
myCamera = null;
}
}
Related
im trying to make basic beacon application in android studio. I just want to scan beacons and list them into the screen. Here are my codes. I took them from somewhere.
public class MainActivity extends ActionBarActivity {
private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId", null, null, null);
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
#Override public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
Log.d("TAG", "Ranged beacons: " + beacons);
}
});
}
#Override
protected void onStart() {
super.onStart();
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override public void onServiceReady() {
try {
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
} catch (RemoteException e) {
Log.e("TAG","Cannot start ranging", e);
}
}
});
}
#Override
protected void onStop() {
super.onStop();
try {
beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS);
} catch (RemoteException e) {
Log.e("TAG", "Cannot stop but it does not matter now", e);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.disconnect();
}
}
Here is my manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.oem.estimote_ibeacon_app" >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/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>
<service
android:name="com.estimote.sdk.service.BeaconService"
android:exported="false"/>
</application>
</manifest>
When i opened application it says "stopped" please help. I have beacons for test. Where is my mistake? Thank you.
it seems that ALL_ESTIMOTE_BEACONS in
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
is null.
enter a valid regionid instead of "regionid" in
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId", null, null, null);
i am new to android. i want to make an app from where i can take pic using camera object. here is my simple code
public class Main extends Activity {
Camera camera;
ImageView iv;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camera = camera.open();
b = (Button) findViewById(R.id.bStartCamera);
iv = (ImageView) findViewById(R.id.imageView1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (camera != null) {
camera.takePicture(null, null, new CallBack());
} else {
Log.d("", "Camera Object is Null");
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (camera != null) {
camera.release();
camera = null;
}
}
class CallBack implements PictureCallback {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d("", "In the Callback Method");
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.homescreensetter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.homescreensetter.Main"
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>
i tested this code on my device which have a back camera but the call back method onPictureTaken was never called when i take picture. please any kind of help will be much appriciated,Thanks
I'm trying to make a Flahlight app, but when I press the "Flashlight" button to turn the flashlight on, the app crashes.
Here's my code:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flashlight"
android:versionCode="1"
android:versionName="1.0" >
<!-- Allows access to the flashlight -->
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.flashlight.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>
java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void toggleFlashlight() {
Camera cam;
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
}
I put the codes in images because I couldn't get the code block to work.
Add parameter View v to public void toggleFlashlight()
as
public void toggleFlashlight(View v)
Change:
public void toggleFlashlight() {
Camera cam;
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
to
public void toggleFlashlight(View v) {
Camera cam;
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
From your logcat, it is seen that you're setting the method for onClick in your XML to toggleFlashlight(). Due to being a method called on a View's click, it must match the signature of other onClick() methods, and have a View parameter.
private void switchOn()
{
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
if(cam == null)
{
cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
}
}
private void switchOff()
{
if(cam != null)
{
cam.stopPreview();
cam.release();
cam = null;
}
}
I'm developing an application in which the wifi state goes OFF when the phonestate is RINGING.
My code is as follows :
phonestateManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phone.state"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/ic_launcher" >
<activity
android:label="#string/app_name"
android:name=".PhonestateActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</activity>
<activity android:name=".WifitoggleActivity" />
<receiver android:name=".ServiceReceiver" />
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</manifest>
PhonestateActivity.java
public class PhonestateActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(PhonestateActivity.this,
ServiceReceiver.class);
startActivity(intent);
}
});
}
}
ServiceReceiver.java
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MyPhoneStateListener phoneListener = new MyPhoneStateListener();
TelephonyManager telephony = (TelephonyManager);
context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, MyPhoneStateListener.LISTEN_CALL_STATE);
}
}
MyPhoneStateListener.java
public class MyPhoneStateListener extends PhoneStateListener {
#SuppressWarnings("unused")
private WifitoggleActivity ss;
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.d("DEBUG", "IDLE");
break;
case TelephonyManager.CALL_STATE_RINGING: {
ss = new WifitoggleActivity();
Log.d("DEBUG", "RINGING");
break;
}
}
}
}
WifitoggleActivity.java
public class WifitoggleActivity extends Activity {
public WifitoggleActivity() {
System.out.print("INSIDE WIFI");
}
/** Called when the activity is first created. */
private WifiManager wifiManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
} else {
wifiManager.setWifiEnabled(true);
}
}
}
The code is just FORCE CLOSEing in my device. Is it a problem with the Manifest file?
Please help me to find a solution.
Thanks in advance guys.
ServiceReceiver is a BroadcastReceiver not an Activity. You are using wrong code in first block.
Find the onClick handler in your code:
public class PhonestateActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1= (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Then remove these two lines:
Intent intent = new Intent(PhonestateActivity.this,ServiceReceiver.class);
startActivity(intent);
and replace them by
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_ANSWER);
registerReceiver(new ServiceReceiver(),intentFilter);
As ServiceReceiver is not an activity.
Edited
Add one more permission:
android.permission.PROCESS_OUTGOING_CALLS
and change
<receiver android:name=".ServiceReceiver">
<intent-filter>
<action android:name=" android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Now remove two line that registering broadcast from oncreate method
Check this link
I am new in android and i would like to lock the phone. So I Read through Device Admin documentation. and have my code looking like this. But it doesnt seem to notice it on my manifest suggests if i have it defined in it which i do
my manifest.xml
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainLauncher"android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Controller"android:label="#string/app_name">
</activity>
<activity android:name=".DeviceAdminSample$Controller"android:label="#string/activity_sample_device_admin">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<receiver android:name=".DeviceAdminSample"android:label="#string/sample_device_admin"android:description="#string/sample_device_admin_description"android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"android:resource="#xml/device_admin_sample" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
</manifest>
My Code
public class DeviceAdminSample extends DeviceAdminReceiver {
public static class Controller extends Activity {
static final int RESULT_ENABLE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
mDeviceAdminSample = new ComponentName(Controller.this, DeviceAdminSample.class);
mEnableButton = (Button)this.findViewById(R.id.button1);
mEnableButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
mDeviceAdminSample);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
});
mDisableButton = (Button)this.findViewById(R.id.button2);
mDisableButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mDPM.removeActiveAdmin(mDeviceAdminSample);
updateButtonStates();
}
});
mForceLockButton = (Button)this.findViewById(R.id.button3);
mForceLockButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i(" In","In the forc lock button");
if (mAM.isUserAMonkey()) {
AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this);
builder.setMessage("You can't lock my screen because you are a monkey!");
builder.setPositiveButton("I admit defeat", null);
builder.show();
return;
}
boolean active = mDPM.isAdminActive(mDeviceAdminSample);
if (active) {
v mDPM.lockNow();
}
}
});
}
void updateButtonStates() {
boolean active = mDPM.isAdminActive(mDeviceAdminSample);
if (active) {
mForceLockButton.setEnabled(true);
} else {
mForceLockButton.setEnabled(false);
}
}
}
}
My Other Activity
package com.examples;
public class MainLauncher extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlauncher);
Button btnLock = (Button)this.findViewById(R.id.button22);
btnLock.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.reenableKeyguard();
}
});
Button btnDevice = (Button)this.findViewById(R.id.button11);
btnDevice.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try{
Intent openScreen = new Intent();
openScreen.setClass(MainLauncher.this, DeviceAdminSample.class);
startActivity(openScreen);
}
catch(Exception e)
{Log.i("DeviceAdmin button",String.valueOf(e));}
}
});
}
}
Have you added a resource under "xml" folder called "device_admin_sample.xml"? It will have permission required for doing a "force lock" for Device administrator to work.