After two days of tests we were able to partially work.
I downloaded the file, but I have no idea where to store it.
I tried to download a picture and the picture appears in the folder /all_downloads
I do not know how to store it in /sdcard/update.
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class Upgrade extends ActionBarActivity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrade);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://android.vrt.ro/tv-update/v1.apk"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///sdcard/download/v1.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
}
}
Use this
request.setDestinationInExternalPublicDir("/updates", "update.apk");
Added in API level 9
public DownloadManager.Request setDestinationInExternalPublicDir (String dirType, String subPath)
Set the local destination for the downloaded file to a path within the
public external storage directory (as returned by
getExternalStoragePublicDirectory(String)).
The downloaded file is not scanned by MediaScanner. But it can be made
scannable by calling allowScanningByMediaScanner().
Parameters dirType the directory type to pass to
getExternalStoragePublicDirectory(String)` subPath the path within the
external directory, including the destination filename Returns this
object Throws IllegalStateException If the external storage directory
cannot be found or created.
You can also use this version
String updatePath = Environment.getExternalStorageDirectory() + File.separator + "Updates" + File.separator + "update.apk";
request.setDestinationUri(Uri.fromFile(new File(updatePath)))
Related
I'm trying to change the notification sound by using channels, and it works perfectly.
I know the channels just support android 8.0 and above but I have a case to turn the app into android 7. So is there a way to change the notification sound in this version?
MainActivity.java
package com.myapp;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.net.Uri;
import android.content.ContentResolver;
import androidx.core.app.NotificationCompat;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "myApp";
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("new_order", "myApp", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setShowBadge(true);
notificationChannel.setDescription("");
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
notificationChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/bell"), att);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{400, 400});
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
}
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
#Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
This question already has answers here:
How to sound notifications sound when new Message arrives from Firebase Realtime Data base
(4 answers)
Closed 4 years ago.
I'm using firebase data base to create my chat applicaiton. Now that I have sucessfully completed my chat application, but when new message arrives I would like to notify user with sound and NOtification in Notification bar even when the app is not running.
I used the below code to do that
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
But it only set alarm when i open the chat activity, then aftearwards when new message arrives it does nothing.
Here is my chat activity code
package com.nepalpolice.mnemonics.chat;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.ToneGenerator;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.RemoteMessage;
import com.nepalpolice.mnemonics.R;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by filipp on 6/28/2016.
*/
public class Chat_Room extends AppCompatActivity{
private Button btn_send_msg;
private EditText input_msg;
private TextView chat_conversation;
private Toolbar mainToolbar;
private String user_name,room_name;
private DatabaseReference root ;
private String temp_key;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
btn_send_msg = (Button) findViewById(R.id.btn_send);
input_msg = (EditText) findViewById(R.id.msg_input);
chat_conversation = (TextView) findViewById(R.id.textView);
user_name = getIntent().getExtras().get("user_name").toString();
room_name = getIntent().getExtras().get("room_name").toString();
mainToolbar = (Toolbar) findViewById(R.id.main_chat);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle(" Room - "+room_name);
root = FirebaseDatabase.getInstance().getReference().child(room_name);
btn_send_msg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String,Object> map2 = new HashMap<String, Object>();
map2.put("name",user_name);
map2.put("msg",input_msg.getText().toString());
message_root.updateChildren(map2);
input_msg.getText().clear();
}
});
root.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String chat_msg,chat_user_name;
private void append_chat_conversation(DataSnapshot dataSnapshot) {
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
chat_msg = (String) ((DataSnapshot)i.next()).getValue();
chat_user_name = (String) ((DataSnapshot)i.next()).getValue();
chat_conversation.append(chat_user_name +" : "+chat_msg +" \n");
}
}
}
Here is my Firebase Data structure file
Firebase Data Structure
Any help is appreciated. Thanks in advance.
If you are using FCM, you need to understand this part of the doc before proceeding:
The onMessageReceived is provided for most message types, with the following exceptions which are listed below:
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default
Messages with both notification and data payload, both background and foreground. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
So if you need to decide the type of payload you re sending to the android device. You may want to go for Message with both Notifications and data payload so that onMessageRecieved() is invoked at all times.
You can find more details Here
I would like to block call from specific number I tried some solution but I get errors.
I tried this solution but it is not working.
https://stackoverflow.com/a/9904826/1937692
It gives
Can not resolve symbol ITelephony
Project Structure:
http://i.hizliresim.com/P02XOd.png
PhoneCallReceiver:
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneCallStateListener customPhoneListener = new PhoneCallStateListener(context);
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}}
ITelephony.aidl:
package com.android.internal.telephony;
interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
PhoneCallStateListener:
package com.example.myapplication;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.android.internal.telephony.ITelephony; //Error Line
public class PhoneCallStateListener extends PhoneStateListener {
private Context context;
public PhoneCallStateListener(Context context){
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String block_number = prefs.getString("block_number", null);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//Turn ON the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Toast.makeText(context, "in"+block_number, Toast.LENGTH_LONG).show();
Class clazz = Class.forName(telephonyManager.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager); //Error Line
//Checking incoming call number
System.out.println("Call "+block_number);
if (incomingNumber.equalsIgnoreCase("+91"+block_number)) {
//telephonyService.silenceRinger();//Security exception problem
telephonyService = (ITelephony) method.invoke(telephonyManager);
telephonyService.silenceRinger();
System.out.println(" in "+block_number);
telephonyService.endCall();
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
//Turn OFF the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
case PhoneStateListener.LISTEN_CALL_STATE:
}
super.onCallStateChanged(state, incomingNumber);
}}
Error - Red Lines:
http://i.hizliresim.com/YD8zQA.png
The interface ITelephony is package-visible and therefore not accessible from outside of the package com.android.internal.telephony.
That's because it is an internal Android API.
you have added ITelephony.AIDL file in your project? and if you have added then your package name must be com/android/internal/telephony/ITelephony.AIDL: for more information Blocking Incoming call. download AIDL file from here
I am trying to read a file as inputstream to fill in the file with additional data. This data is then supposed to be sent over to a second activity which unwraps the data and displays it on the screen. this is my code
package com.example.daniel.finalproject;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class Secondactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void Proceed(View view) {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
}
}
However this line: InputStream is = am.open("madlibsimple.txt");
returns the error. madlibsimple.txt is in the assetsfolder, but I
don't know what goes wrong. Any help would be much appreciated.
open(String file) can throw an error (i expect IOException) that you have to catch with an
try {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
} catch (Exception e) {
e.printStacktrace();
}
statement.
This whole topic is not about what goes wrong, but what COULD go wrong
For more information on the topic of exceptions and errorhandling you can click here
I would like to open a pdf file ( which is available in Downloads folder in Android phone) during on click on the 'pdfButton'
While performing the action, nothing happens, there are either no errors logged or pdf file is displayed. Could some one please help ?
package com.mycompany.myfirstglapp;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
/**
* Created by admin on 1/11/2016.
*/
public class PdfActivity extends Activity {
private SurfaceView surface;
Button pdfButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
surface = (SurfaceView) findViewById(R.id.pdfSurface);
pdfButton = (Button) findViewById(R.id.pdfView);
pdfButton .setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// On click will call the showPdf method to display the pdf file in sd card or downloads
showPdf(view);
}
});
}
public void showPdf(View view) {
// The pdf file [LawsofthegamewebEN_Neutral.pdf] is avaialble in Android > Downloads folder.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfActivity.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
}
If you step through the code with your debugger, or put more logging statements in, I suspect that you will find that file.exists() returns false. And, at the moment, you do not do anything in that case.
I would like to open a pdf file ( which is available in Downloads folder in Android phone)
That is not where your code is looking. Replace:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/LawsofthegamewebEN_Neutral.pdf");
with:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "LawsofthegamewebEN_Neutral.pdf");
Also note that your file.exists() call means that you will need to hold the READ_EXTERNAL_STORAGE permission.