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.
Related
When I click the share button, it opens and shows some apps, but I click one app, for eg, WhatsApp it open and I choose the contact but when clicking the send button it shows "file can't be send". where I made a mistake, please help me to solve this code.
here I attached code for the share button.
//get an image from imageview
Drawable drawable = imageView.getDrawable();
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
//sharing image
try {
File file = new File(MainActivity.this.getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file.setReadable(true, false);
//sharing intent
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file);
intent.setType("image/png");
startActivity(Intent.createChooser(intent, "Share via"));
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Try adding
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
here is my android manifest file,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.photoeditor">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android-hardware.camera"
android:required="false" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationID}.provider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"
tools:replace="android:resource"/>
</provider>
</application>
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 :)
I am trying to Scan the QR code using com.google.zxing.client.android.SCAN but it does not opening the camera and always responding with "Scan was Cancelled!" toast message for Sony Xperia C only.
ScanQR.java
ScanBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Toast toast = Toast.makeText(this, "Content:" + contents,
Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
Toast toast = Toast.makeText(this, "Scan was Cancelled!",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.test.ScanQR"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try something like this.
startActivityForResult(
new Intent(
Emailtry.this,
com.google.zxing.client.android.CaptureActivity.class),
11);
I have a activity and one button make shortcut + custom intent with my action inside. After I'm click the button, it's work well, a shortcut already on homescreen. Then I click shortcut, main activity can not catch the intent in my receiver class. Where am I wrong?
Main Activity
I have rigister Reciever in onCreate(), with intent filter.
registerReceiver(new MyReceiver(), new IntentFilter("nhq.intent.flashlight"));
This is my Reciever class inside MainActivity
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.v("$$$$$$", "In Method: ACTION_SCREEN_OFF");
// onPause() will be called.
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.v("$$$$$$", "In Method: ACTION_SCREEN_ON");
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.v("$$$$$$", "In Method: ACTION_USER_PRESENT");
// Handle resuming events
}
}
}
When I click the button make shortcut I run the function
private void makeShortcut() {
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setAction("nhq.intent.flashlight");
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"Flash Light");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(),R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
//finish();
}
I also defined reciever in manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nhq.fashlight"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<!-- Camera Requirement -->
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<!-- Camera Permissions -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- Features -->
<uses-feature android:name="android.hardware.camera.flash" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="nhq.fashlight.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTask" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CREATE_SHORTCUT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name="nhq.fashlight.MainActivity$MyReceiver" >
<intent-filter>
<action android:name="nhq.intent.flashlight" />
</intent-filter>
</receiver>
</application>
</manifest>
I've re-read the question (sorry) and it seems you have a typo in your package names:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nhq.fashlight"
shortcutIntent.setAction("nhq.intent.flashlight");
That maybe why the shortcut doesn't work.
i think that need addAction for ACTION_SCREEN_OFF, ON, PRESENT.
like this
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
also add ACTION_SCREEN_ON,ACTION_USER_PRESENT filter.addAction too.
then receive intent action
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.v("$$$$$$", "In Method: ACTION_SCREEN_OFF");
// onPause() will be called.
}
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>