android camera led flash light widget not working - android

I am trying to build and led flash light widget but compiler is not showing any error whenever I try to press widget there show widget loading problem
and android studio does not show any error I am beginner so please help me. Thanks in advance
Meanifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mateen.flash_light_widget">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".NewAppWidget" android:icon="#drawable/example_appwidget_preview" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/new_app_widget_info" />
</receiver>
<receiver android:name="FlashlightWidgetReceiver">
<intent-filter>
<action android:name="COM_FLASHLIGHT"></action>
</intent-filter>
</receiver>
</application>
</manifest>
appwidgetprovider class
public class NewAppWidget extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Intent receiver = new Intent(context, FlashlightWidgetReceiver.class);
receiver.setAction("COM_FLASHLIGHT");
receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.new_app_widget);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
}
recevier there is error I think compiler is also not showing any error
public class FlashlightWidgetReceiver extends BroadcastReceiver {
private static boolean isLightOn = false;
private static Camera camera;
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
if(isLightOn) {
views.setImageViewResource(R.id.button, R.drawable.example_appwidget_preview);
} else {
views.setImageViewResource(R.id.button, R.drawable.example_appwidget_preview);
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, NewAppWidget.class),
views);
if (isLightOn) {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
isLightOn = false;
}
} else {
// Open the default i.e. the first rear facing camera.
camera = Camera.open();
if(camera == null) {
Toast.makeText(context,"noCamera", Toast.LENGTH_SHORT).show();
} else {
// Set the torch flash mode
Camera.Parameters param = camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
try {
camera.setParameters(param);
camera.startPreview();
isLightOn = true;
} catch (Exception e) {
Toast.makeText(context,"no flash", Toast.LENGTH_SHORT).show();
}
}
}
}
}
layout file for widget
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialKeyguardLayout="#layout/new_app_widget"
android:initialLayout="#layout/new_app_widget"
android:minHeight="40dp"
android:minWidth="40dp"
android:previewImage="#drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="86400000"
android:widgetCategory="home_screen|keyguard"></appwidget-provider>

add these permissions to your manifest
<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" />

i found solution In order to work, the camera needs a surface to turn on.
so after camera.startPreview() i wrote this piece of lines
surfaceTexture = new SurfaceTexture(0);
camera.setPreviewTexture(surfaceTexture);
it solved my problem thanks alot :)

Related

Android AppWidget Config Activity not working on device

I have an AppWidget with a configuration activity that launches when the widget is added to the home screen. It works perfectly fine on the emulator, but when I load on a physical device, the widget is not added to the home screen after the configuration activity finishes. Both the emulator and the hardware device are a Samsung Galaxy S7, API level 23, with the app's target API set to 26.
Even if I remove all my logic and just have an empty widget and an empty configuration activity, it does not work on my device. But as soon as I remove the activity from the appwidget-provider xml tag, it works fine.
Any ideas? I'm thinking it must be something with the system settings, maybe the storage options?
I notice these errors that appear when running on the device, but they don't look directly related to the problem
E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy#e5f8725
E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#57800fa
E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#57800fa
Configuration Activity
public class ConfigureActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure);
setResult(RESULT_CANCELED);
}
public void onDoneClick(View view) {
setResult(RESULT_OK);
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, this, WidgetActivity.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
sendBroadcast(intent);
finish();
}
}
Widget Activity
public class WidgetActivity extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_activity);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.widget">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:installLocation="internalOnly"
android:theme="#style/AppTheme">
<activity android:name=".ConfigureActivity">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<receiver android:name=".WidgetActivity">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_activity_info" />
</receiver>
</application>
</manifest>
widget_activity_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:configure="com.example.widget.ConfigureActivity"
android:initialKeyguardLayout="#layout/widget_activity"
android:initialLayout="#layout/widget_activity"
android:minHeight="110dp"
android:minWidth="250dp"
android:previewImage="#drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="86400000"
android:widgetCategory="home_screen|keyguard">
</appwidget-provider>

Lock or turn off the screen programmatically

I want to turn off / lock the screen of my device programmatically.
For the moment, when I try :
DevicePolicyManager mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mDPM.lockNow();
I have this error :
java.lang.SecurityException: No active admin owned by uid 10176 for policy #3
This is my AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="opteamit.com.belami" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application...
What is wrong ?
Well something with high necessity can't finished with two lines of code, lock off screen required device admin. you may follow this :
private void lock() {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
DevicePolicyManager policy = (DevicePolicyManager)
getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
policy.lockNow();
} catch (SecurityException ex) {
Toast.makeText(
this,
"must enable device administrator",
Toast.LENGTH_LONG).show();
ComponentName admin = new ComponentName(context, AdminReceiver.class);
Intent intent = new Intent(
DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
context.startActivity(intent);
}
}
}
and AdminReceiverClass:
public class AdminReceiver extends DeviceAdminReceiver {
public static final String ACTION_DISABLED = "device_admin_action_disabled";
public static final String ACTION_ENABLED = "device_admin_action_enabled";
#Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_DISABLED));
}
#Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_ENABLED));
}
}
also we need declares the security policies used in metadata so for examples with Path android:resource="#xml/device_admin_sample" :
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>
in our case we just need :
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>`
Now declare it in our manifist.xml :
<receiver
android:name=".AdminReceiver"
android:label="#string/device_admin"
android:description="#string/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>`
Hope it will Help you.
See user6490462 answer below.
private void lock() {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
DevicePolicyManager policy = (DevicePolicyManager)
getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
policy.lockNow();
} catch (SecurityException ex) {
Toast.makeText(
this,
"must enable device administrator",
Toast.LENGTH_LONG).show();
ComponentName admin = new ComponentName(context, AdminReceiver.class);
Intent intent = new Intent(
DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
context.startActivity(intent);
}
}
}
For those of us who landed here from google and weren't able to get the admin request to popup, I ended up solving it by making sure that I started the activity from a currently running Activity (thus, calls would not need the context. in front of them. While some may have had luck with intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) from a service, I had to move the call into an Activity.
ComponentName admin = new ComponentName(context, AdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
startActivity(intent);
This worked for me after following user6490462's instructions but I had to tweak the Intent slightly
Even with these changes, for some reason I could not get the activity window to pop up to approve the device admin privilege's. But when I went into Biometrics and security -> Other security settings -> Device admin apps I could see my app there waiting to have its admin privilege's approved.
ComponentName admin = new ComponentName(getApplicationContext(), AdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Allow this app to turn screen off");
startActivity(intent);

Codes for call recording in android

I am making and application that records calls. Here is my code to record a call and save the file in the SD card under songs folder. But the problem is that this code was working fine but later it is not working. I cannot find what is the problem. Can you please help me out?
My Broad cast receiver:
public class BrCallReceive extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent i) {
Bundle extras = i.getExtras();
Intent x = new Intent (c, EavesDropperActivity.class);
x.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("DEBUG", state);
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.w("DEBUG", "MATCHES");
Toast.makeText(c, "Launching record APP !", Toast.LENGTH_LONG).show();
c.startActivity(x);
}
}
}
}
My Recording activity:
public class EavesDropperActivity extends Activity {
/** Called when the activity is first created. */
MediaRecorder m_recorder = new MediaRecorder();
TelephonyManager t_manager ;
PhoneStateListener p_listener ;
String record_state;
Uri file;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
Toast.makeText(getBaseContext(),
"Executing Activity",
Toast.LENGTH_LONG).show();
t_manager = (TelephonyManager) getSystemService (Context.TELEPHONY_SERVICE);
p_listener = new PhoneStateListener() {
#Override
public void onCallStateChanged (int state, String incomingNumber) {
switch (state) {
case (TelephonyManager.CALL_STATE_IDLE) :
stop_recorder();
//t_manager.listen(p_listener, PhoneStateListener.LISTEN_NONE);
//finish();
break;
case (TelephonyManager.CALL_STATE_OFFHOOK) :
start_recorder();
break;
case (TelephonyManager.CALL_STATE_RINGING) :
break;
}
}
};
t_manager.listen(p_listener, PhoneStateListener.LISTEN_CALL_STATE);
return;
}
public void start_recorder () {
m_recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
m_recorder.setOutputFormat(OutputFormat.THREE_GPP);
m_recorder.setOutputFile(Environment.getExternalStorageDirectory()+"/songs/audionew.3gpp");
m_recorder.setAudioEncoder(AudioEncoder.AMR_NB);
try {
m_recorder.prepare();
m_recorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop_recorder () {
m_recorder.stop();
m_recorder.release();
Uri file = Uri.fromFile(
new File(Environment.getExternalStorageDirectory(),"/songs/audionew.3gpp"));
Toast.makeText(getBaseContext(),
"record stored at " + file.toString(),
Toast.LENGTH_LONG).show();
t_manager.listen(p_listener, PhoneStateListener.LISTEN_NONE);
finish();
}
}
My manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testapp.EavesDropperActivity"
android:label="#string/app_name" >
</activity>
<receiver android:name="BrCallReceive" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
I think the broadcast receiver is not getting activated wile i am calling my phone.
How do you know your broadcast receiver is not working? Place a Log message inside onReceive() right at the beginning. It might be that your extras == null
But how to make my receiver functional now?
Check out example #5 and just follow the same steps.
Bro i dont think activity will get launched.
Well, it does: You are starting it in your onReceive():
Intent x = new Intent (c, EavesDropperActivity.class);
c.startActivity(x);
However, you are not setting any content in your Activity i.e no UI screen is presented because you have this line commented in onCreate() of EavesDropperActivity Activity:
//setContentView(R.layout.main);
So, you need to think hard on what you are trying to achieve in EavesDropperActivity
HTH.
Put this
<android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
in mainfest file for broadcast receiver.
Add your package name to your receiver class as,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testapp.EavesDropperActivity"
android:label="#string/app_name" >
</activity>
<receiver android:name="com.example.testapp.BrCallReceive" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
</application>

Android 4.x devices receive GCM messages, but Android 2.3 devices Don't

My android app never receives GCM messages on 2.3 devices, but it does on 4.x devices. I can register all devices (2.3 and 4.x) successfully. I thought it might have something to do with this issue, but it seems like I have my android manifest configured properly. Would anyone be able to eyeball my IntentService and BroadcastReceiver and see if they notice any problems? Any help would be greatly appreciated. Note that onHandeIntent() is never called for Android 2.3 when sending notifications while I have the debugger attached. I checked 4.x devices, and they do trigger the debugger in onHandleIntent().
Thanks!
Android Manfest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="my.package.matchtracker.permission.C2D_MESSAGE" />
<permission android:name="my.package.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="my.package" />
</intent-filter>
</receiver>
<service android:name=".NotificationIntentService" android:enabled="true" />
<activity android:name="com.gigya.socialize.android.GSWebViewActivity" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Broadcast Receiver:
package my.package;
import android.app.*;
import android.content.*;
public class GcmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationIntentService.runIntentInService(context, intent);
setResultCode(Activity.RESULT_OK);
}
}
Notification Intent Service
public class NotificationIntentService extends IntentService {
private String TAG = "NotificationIntentService";
public NotificationIntentService() {
super(AppConstants.GCM_SENDER_ID);
}
public NotificationIntentService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
private static PowerManager.WakeLock sWakeLock;
private static final Object LOCK = NotificationIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized(LOCK) {
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, NotificationIntentService.class.getName());
context.startService(intent);
}
public final void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
//don't care.
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized(LOCK) {
sWakeLock.release();
}
}
}
private void handleMessage(Intent intent) {
Bundle b = intent.getExtras();
String text = b.getString("text"),
title = b.getString("title"),
largeImageUrl = b.getString("largeImageUrl");
Log.i(TAG, "Message is " + text);
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Bitmap bit=null;
if (largeImageUrl != null && !largeImageUrl.isEmpty()) {
try{bit = BitmapFactory.decodeStream((InputStream)new URL(largeImageUrl).getContent());
} catch (Exception e){}
}
NotificationCompat.Builder nc = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true) //notification disappears when clicked
.setContentIntent(PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
//bit = Bitmap.createScaledBitmap(bit, android.R.dimen.notification_large_icon_width, android.R.dimen.notification_large_icon_height, true);
if (bit != null) nc.setLargeIcon(bit);
nm.notify(0, nc.build());
}
}
The first potential problem I can see is this :
The package name in the permission element is not the same as the one in the uses-permission element. In my app (which targets Android 2.2) they are identical.
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="my.package.matchtracker.permission.C2D_MESSAGE" />
<permission android:name="my.package.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
If you are using product flavor with different applicationId, see my answer to the question GCM messages are not received on android 2.3.6 v but working fine on android 4.X v
GCM need google play services installed on device but in version 2.3 it's not installed by default.

StartActivity from broadcastreceiver

Onreceive method will crash app at context.startActivity(Intent.createChooser(sendIntent, "Send"));
It works fine in oncreate method but do not work in broadcastreceiver class.
Can anybody knows reason. I am new android programmer.
Thanks in advance.
public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
takePictureNoPreview(context);
String imagePath="test.jpeg";
Intent sendIntent = new Intent(Intent.ACTION_SEND);
// sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body", "I Send you pic.");
sendIntent.putExtra("address", phoneNumber);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(dataFile));
// context.startActivityForResult(sendIntent, 1);
context.startActivity(Intent.createChooser(sendIntent, "Send"));
// context.startActivity(sendIntent);
}
}
}
public void takePictureNoPreview(Context context){
// open back facing camera by default
Camera myCamera= Camera.open();//openFrontFacingCameraGingerbread();
if(myCamera!=null){
try{
//set camera parameters if you want to
//...
// here, the unused surface view and holder
SurfaceView dummy=new SurfaceView(context);
myCamera.setPreviewDisplay(dummy.getHolder());
myCamera.startPreview();
myCamera.takePicture(null, null, photoCallback);
} catch (IOException e) {
e.printStackTrace();
}finally{
// myCamera.close();
}
}else{
Toast toast = Toast.makeText(context, "No front Facing camera", Toast.LENGTH_LONG);
toast.show();
}
}
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Save the image JPEG data to the SD card
FileOutputStream fos = null;
// camera.startPreview();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
StudentDemo.iView.setImageBitmap(bmp);
try {
fos = new FileOutputStream(dataFile,true);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*new SavePhotoTask().execute(data);
camera.startPreview();*/
}
};
}
Android manifest file is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gen.stud"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9"
android:targetSdkVersion="9"
/>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Demo"
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=".StudentDemo"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.StudentDemo" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Try:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "I Send you pic.");
sendIntent.putExtra("address", phoneNumber);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(dataFile));
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(Intent.createChooser(sendIntent, "Send"));
Whenever launching an Activity from outside a UI related context (like a Service or a BroadcastReceiver), you need to attach the FLAG_ACTIVITY_NEW_TASK to the intent.

Categories

Resources