android -How to update application inside application - android

I've seen this in some application , the application size is about 6 mb but it download a file about 100kb and update the application .
it's very interesting , I've searched alot but I couldn't find any way to do it .
How can I do so ?
thanks

I do it using the below class, but it does require downloading the new APK, so it may not be exactly what you need. It is done this way because we do not use the play store.
If there is an update available, start the Runnable class.
It starts the download, and when the download is completed it asks if you want to update, then starts the update.
All you need to do is figure out how to host the APK file. I use a windows server and IIS7, with a mime setup so it is recognized by android as an installable APK.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class GetUpdate implements Runnable{
Context cxt;
String line;
String filepath = "";
int continueornot=0;
ProgressBar progBar;
Button buttOk;
DownloadManager mgr=null;
long lastDownload=-1L;
public GetUpdate(Context contextIn, String lineIn, ProgressBar progressBar,Button okButtIn){
cxt = contextIn;
line = lineIn;
this.progBar = progressBar;
this.buttOk = okButtIn;
}
#Override
public void run() {
filepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the download?");
// Set an EditText view to get user input
//final EditText serverURL = new EditText(cxt);
//alert.setView(serverURL);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//String tempFilepath = cxt.getExternalFilesDir("/MyFileStorage/").getAbsolutePath();
File myExternalFile = new File(filepath);
File[] sdDirList = myExternalFile.listFiles();
if(sdDirList != null){
for(int x=0;x<sdDirList.length;x++){
String fileNameString = sdDirList[x].toString();
System.out.println("File: " + sdDirList[x].toString());
if(fileNameString.trim().equalsIgnoreCase("podcodes.txt")
||fileNameString.trim().equalsIgnoreCase("vehiclesTrailers.txt")
||fileNameString.trim().equalsIgnoreCase("checks.txt")
||sdDirList[x].toString().endsWith(".apk")){
sdDirList[x].delete();
}
}
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
AlertDialog.Builder alert = new AlertDialog.Builder(cxt);
alert.setTitle("Update Availible");
alert.setMessage("Start the update?");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(cxt.getApplicationContext(), "Updating!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
String lastDownloaded = mgr.getUriForDownloadedFile(lastDownload).toString();
//String lastDownloadFileName = lastDownloaded.substring(lastDownloaded.lastIndexOf("/")+1);
intent.setDataAndType(Uri.parse(lastDownloaded), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cxt.startActivity(intent);
Globals.setExit(true);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
});
alert.show();
}
};
mgr=(DownloadManager)cxt.getSystemService(Context.DOWNLOAD_SERVICE);
cxt.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
BroadcastReceiver onNotificationClick=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText(ctxt, "Downloading InCab Update!", Toast.LENGTH_LONG).show();
}
};
cxt.registerReceiver(onNotificationClick,
new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
Uri uri=Uri.parse(Globals.getServerURL()+"/LatestAndroid/"+line.trim());
//Environment
// .getExternalStoragePublicDirectory("MyFileStorage/"+line.trim())
// .mkdirs();
lastDownload=
mgr.enqueue(new DownloadManager.Request(uri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(true)
.setTitle(line.trim())
.setDescription("Incab Update.")
.setDestinationInExternalFilesDir(cxt,"MyFileStorage", line.trim()));
Toast.makeText(cxt.getApplicationContext(), "Downloading!", Toast.LENGTH_LONG).show();
continueornot=1;
progBar.setVisibility(View.VISIBLE);
buttOk.setVisibility(View.VISIBLE);
buttOk.setText("Downloading..");
buttOk.setEnabled(false);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
continueornot=2;
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
//cancel(true);
}
});
alert.show();
progBar.setVisibility(View.GONE);
buttOk.setText("OK");
buttOk.setEnabled(true);
buttOk.setVisibility(View.VISIBLE);
}
}

Related

Bluetooth app made with library (https://github.com/OmarAflak/Bluetooth-Library) crashes

I'm working on a simple app, essentially to send data over Bluetooth.
My MainActivity:
package in.justrobotics.jrbluetoothcontrol;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import me.aflak.bluetooth.Bluetooth;
import me.aflak.bluetooth.BluetoothCallback;
import me.aflak.bluetooth.DiscoveryCallback;
public class MainActivity extends AppCompatActivity {
Bluetooth bluetooth;
private ArrayAdapter<String> mBTArrayAdapter;
String address,name;
public void composeEmail(String message) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
intent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "shlokj#gmail.com" });
intent.putExtra(Intent.EXTRA_SUBJECT, "Would like to get in touch");
intent.putExtra(Intent.EXTRA_TEXT, message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
public void sendEmail () {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Send a message: ");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Message = input.getText().toString();
composeEmail(Message);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothOn();
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();
bluetooth = new Bluetooth(getApplicationContext());
if (bluetooth==null){
Toast.makeText(getApplicationContext(),"Bluetooth null",Toast.LENGTH_SHORT).show();
}
if (bluetooth!=null){
Toast.makeText(getApplicationContext(),"Bluetooth not null",Toast.LENGTH_SHORT).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
Button openController = (Button) findViewById(R.id.open_controller);
openController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startController = new Intent(MainActivity.this,ControllerActivity.class);
//startController.putExtra("BLUETOOTH_CONNECTED_THREAD",mConnectedThread);
startActivity(startController);
}
});
Button openAccelController = (Button) findViewById(R.id.open_accel_controller);
openAccelController.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent startControllerAccel = new Intent(MainActivity.this,AccelerometerControl.class);
startActivity(startControllerAccel);
}
});
bluetooth.setBluetoothCallback(new BluetoothCallback() {
#Override
public void onBluetoothTurningOn() {
}
#Override
public void onBluetoothOn() {
}
#Override
public void onBluetoothTurningOff() {
}
#Override
public void onBluetoothOff() {
}
#Override
public void onUserDeniedActivation() {
}
});
bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
#Override public void onDiscoveryStarted() {}
#Override public void onDiscoveryFinished() {}
#Override public void onDeviceFound(BluetoothDevice device) {}
#Override public void onDevicePaired(BluetoothDevice device) {}
#Override public void onDeviceUnpaired(BluetoothDevice device) {}
#Override public void onError(String message) {}
});
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_btdevices, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select your device");
alertDialog.setMessage("A JR Bluetooth device name is of the form JR_X");
ListView devicesListView = (ListView) convertView.findViewById(R.id.mDevicesListView);
devicesListView.setAdapter(mBTArrayAdapter);
devicesListView.setOnItemClickListener(mDeviceClickListener);
alertDialog.show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
String connectStatus="";
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
//mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
name = info.substring(0, info.length() - 17);
if (bluetooth.isConnected()){
connectStatus="Connected";
}
if (!bluetooth.isConnected()){
connectStatus="Not connected";
}
Toast.makeText(getBaseContext(), connectStatus, Toast.LENGTH_SHORT).show();
bluetooth.connectToAddress(address);
Toast.makeText(getBaseContext(), "Connected (hopefully)", Toast.LENGTH_SHORT).show();
bluetooth.send("test");
Toast.makeText(getBaseContext(), "Sent data (hopefully)", Toast.LENGTH_SHORT).show();
}};
#Override
protected void onStart() {
super.onStart();
bluetooth.onStart();
bluetooth.enable();
}
#Override
protected void onStop() {
super.onStop();
bluetooth.onStop();
}
private void bluetoothOn(){
if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
//mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
}
Stack traces:
2019-04-09 20:16:48.222 23737-23737/in.justrobotics.jrbluetoothcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.justrobotics.jrbluetoothcontrol, PID: 23737
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:185)
at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:201)
at in.justrobotics.jrbluetoothcontrol.MainActivity$7.onItemClick(MainActivity.java:197)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1164)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3154)
at android.widget.AbsListView$3.run(AbsListView.java:4097)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
The custom Bluetooth class: https://github.com/OmarAflak/Bluetooth-Library/blob/master/bluetooth/src/main/java/me/aflak/bluetooth/Bluetooth.java
My code is crashing at the line bluetooth.send("test"); with a NullPointerException, and I can't see why. I'm a beginner with Bluetooth on Android; help will be appreciated.
The final outcome I hope I will be able to get is to simply connect to a device and send data, and even that isn't happening.
Edit: I'm facing another problem as well now. I pass the String address to the second activity (https://gist.github.com/shlokj/12c4e2c62ca0f5284c5c3c041775654f) from the first activity (https://gist.github.com/shlokj/f80d0902ad1a366ab03e178164968cfb) through an intent. There, I try to connect at line 163 (bluetoothObject.connectToAddress(address);), and it crashes with a NullPointerException. I have no idea why, because I check that the Bluetooth object and address are not null with an if statement. Stack traces: https://gist.github.com/shlokj/56e3c9e311dea6f77a1acd8953a317c8 Whole repository: https://github.com/shlokj/JR-Bluetooth-Control.
So, in a nutshell, I now need to be also able to connect properly, leave alone sending data.
I just went through the library link you provided and it seems someone else faced the similar issue given here:
https://github.com/OmarAflak/Bluetooth-Library/issues/16
And it turned out be the connection wasn't established yet,so before calling send please check if the device is connected by using isConnected() function.
You shouldn't call send before the connection is established properly.you can set callback for the same using setDiscoveryCallback and do work inside most probable after you get confirmation in void onDevicePaired(BluetoothDevice device).
Edit 1: from the comments.
Are you sure it is in onDevicePaired() that I am supposed to send
data?
Maybe not,I think i misunderstood the example given by library author,now i think you should do it on onDeviceConnected.
Is there any other method that gets called when it is connected?
Yes,you can set a callback for that using following:
bluetooth.setDeviceCallback(new DeviceCallback() {
#Override
public void onDeviceConnected(BluetoothDevice device) {
// do your work here.
}
#Override
public void onDeviceDisconnected(BluetoothDevice device, String message) {
}
#Override
public void onMessage(String message) {
}
#Override
public void onError(String message) {
}
#Override
public void onConnectError(BluetoothDevice device, String message) {
}
});
Edit 2:
There, I try to connect at line
163(bluetoothObject.connectToAddress(address);), and it crashes with a
NullPointerException.
This crash happens because BluetoothAdapter isn't initialized yet,so when you call bluetoothObject.connectToAddress(address) it throws NullPointerException.
You need to initialize that before connecting as following:
bluetoothObject = new Bluetooth(getApplicationContext());
bluetoothObject.onStart();//this is the line that initializes adapter.
bluetoothObject.enable();

Android : Evaluate Dialog

I want to evaluate a Dialog under Android.
My problem is that the Dialog does not wait
with returning a value until I pressed a
button. And when I use a Semaphore the
program hangs at Semaphore.acquire().
Why does it hang at Semaphore.acquire()?
Can you see where I go wrong?
Here is the main activity
package com.example.modaldialog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDialog meinDialog = new mDialog(this);
if (meinDialog.ShowMyModalDialog() == 1)
Toast.makeText(this, "Pressed Button 1",
Toast.LENGTH_LONG).show();
}
}
and here the dialog class
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
import java.util.concurrent.Semaphore;
import android.app.Activity;
import java.lang.Runnable;
public class mDialog
{
int pressedButtonID;
Activity act;
private final Semaphore dialogSemaphore;
mDialog(Activity act_in)
{
act = act_in;
dialogSemaphore = new Semaphore(0, true);
};
final Runnable mMyDialog = new Runnable()
{
public void run()
{
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogSemaphore.release();
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogSemaphore.release();
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
};
public int ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
act.runOnUiThread(mMyDialog);
try
{
dialogSemaphore.acquire();
}
catch (InterruptedException e)
{
}
return(pressedButtonID);
}
}
I am not much aware about the Semaphore but you can achieve the same with Interface. I have updated your code please find it below,
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class mDialog
{
int pressedButtonID=0;
private HandleDialogEvent dialogEvent;
mDialog(HandleDialogEvent dialogEvent)
{
this.dialogEvent = dialogEvent;
}
public void ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
public interface HandleDialogEvent{
public void getDialogId(int Id);
}
}

Android - Click on image multiple times to open dialog

I am looking for a code that would let me click on an imageView 3 times to open a dialog box. That would be very helpful, thank you!
Here is my code:
package natanrosenfeld.texteditor;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import com.natanrosenfeld.texteditor.R;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Handler;
import java.lang.Runnable;
public class CreditsActivity extends ActionBarActivity{
private AtomicInteger mCounter = new AtomicInteger();
private Handler handler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
mCounter = new AtomicInteger();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_credits);
ImageView img = (ImageView) findViewById(R.id.imageView);
addClickToImage(img);
}
public void addClickToImage(ImageView imageView) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(mRunnable);
handler.postDelayed(mRunnable, 1000);
if (mCounter.incrementAndGet() == 2) {
//Display your dialog fragment
new AlertDialog.Builder(getApplicationContext())
.setTitle("Easter Egg")
.setMessage("Easter Egg...")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
}
});
}
}
ddmlib: Broken pipe
java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
at com.android.ddmlib.Client.sendAndConsume(Client.java:675)
at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:342)
at com.android.ddmlib.Client.requestAllocationStatus(Client.java:521)
at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
at
com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:633)
at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)
Here you have a way to handle the 3 clicks, even if you want to manipulate the counter from other threads. It adds the click listener and waits 1 second to put the counter of clicks to 0.
public class MyActivity extends Activity{
private AtomicInteger mCounter = new AtomicInteger();
private Handle handler = new Handler();
private Runnable mRunnable = new Runnable(){
#Override
public void run(){
mCounter = new AtomicInteger();
}
}
public void onCreate(Bundle savedInstance){
...
ImageView myImage = (ImageView) findViewById(R.id.imageView);
addClickToImage(myImage);
}
public void addClickToImage(ImageView image){
image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
handler.removeCallback(mRunnable);
handler.postDelayed(mRunnable, 1000);
if(mCounter.incrementAndGet() == 3){
//Display your dialog fragment
}
}
});
}
}
Error 2
You are opening your dialog by providing the application context. Here is the line:
new AlertDialog.Builder(getApplicationContext())
The only context that can open dialogs is the current activity context, never the application one. So to fix this error:
new AlertDialog.Builder(CreditsActivity.this)

Receiver not asking user to accept file

I am having some difficulty sending files over Bluetooth. After it attempts to send the file, it will list the transfer as having 'failed' with an 'unknown file' error. I have double-checked my file path but am still having this problem. Do you guys see anything that I am missing? The target phone that is supposed to receive the file isn't showing the incoming file notification that asks the user to accept it or not. I believe this is where the failure is. Do you guys know how to pass the 'permission asking' (I guess we can call it that) to the target device?
//some code used from
// http://examples.javacodegeeks.com/android/core/ui/progressdialog/android-progressdialog-example/
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
package com.project.BluetoothTransfer_v1000;
import java.io.File;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("DefaultLocale")
public class TransferFragment extends Fragment{
private TextView filePathTextView;
private Button startTransferButton;
private ImageView bluetoothImage;
ProgressDialog transferDialog;
Handler updateBarHandler;
private static final int REQUEST_BLUETOOTH = 1;
private static final int DISCOVER_DURATION = 300;
Context context;
ArrayAdapter mArrayAdapter;
long timeCheckStart = 0;
long timeCheckEnd = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//set the user interface layout for this activity
setRetainInstance(false);
View v = inflater.inflate(R.layout.activity_bluetooth_transfer, parent, false);
context = this.getActivity();
filePathTextView = (TextView) v.findViewById(R.id.file_path_textView);
startTransferButton = (Button) v.findViewById(R.id.start_transfer_button);
bluetoothImage = (ImageView) v.findViewById(R.id.bluetooth_imageView);
bluetoothImage.setClickable(true);
startTransferButton.setOnClickListener(new View.OnClickListener() {
//start transfer processes
#Override
public void onClick(View v){
//check to make sure the file path text view != null
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = -1;
//ensure the device being used has bluetooth capability
if (filePathTextView.getText().toString().length() > 4 && btAdapter != null){
//check-enable bluetooth
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//make the device discoverable and check to make sure device isn't already discoverable
if (timeCheckStart == 0 || System.currentTimeMillis() - 60000 > timeCheckStart){
timeCheckStart = System.currentTimeMillis();
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60);
startActivity(discoverableIntent);
}
// /storage/emulated/0/Test.jpg
// /storage/extSdCard/Test.jpg
String filePath = filePathTextView.getText().toString();
Toast.makeText(context, filePath, Toast.LENGTH_LONG);
String fileType = filePath.substring(filePath.length()-3,filePath.length()).toLowerCase();
//handles the sending of different file types
//################## where im having trouble ######################################
switch (fileType){
case "jpg": //allow to fall through to png
case "png": Intent pictureIntent = new Intent(Intent.ACTION_SEND);
pictureIntent.setType("image/*");
pictureIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(pictureIntent, "Send Image"));
break;
case "mp3": Intent audioIntent = new Intent(Intent.ACTION_SEND);
audioIntent.setType("audio/*");
audioIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(audioIntent, "Send Audio"));
break;
case "txt": Intent textIntent = new Intent(Intent.ACTION_SEND);
textIntent.setType("text/*");
textIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
startActivity(Intent.createChooser(textIntent, "Send Text"));
break;
default: new AlertDialog.Builder(context).setTitle("Alert")
.setMessage("The file type submitted is not supported: ("+fileType+")")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show(); break;
}//end fileType switch
}//if text view null (if)
else {
//alert user to input file path
new AlertDialog.Builder(context).setTitle("Error")
.setMessage("Please insert a filename to send and be sure to include the type extension.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}//bt equipped/text view null check (else)
}//end anon class
});
bluetoothImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//display dialog showing program specs and creators
new AlertDialog.Builder(context).setTitle("About")
.setMessage("Created by:"+"\n"+ "Hal, Chris, and Roger")
.setPositiveButton("Awesome!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
});
return v;
}
}
Maybe this answer can help you:
https://stackoverflow.com/a/19618432/3743093
In short: you can't pass an URI created with
Uri uri = Uri.parse(String);
as in
pictureIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
beacuse it lacks info like TITLE and MIME_TYPE.
That's the reason why file type is unknown (missing) and throws this error.
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/*");
Uri uri = getContentResolver().insert(Uri.parse(filename),
values);
pictureIntent.putExtra(Intent.EXTRA_STREAM, uri);
Hope this helps.

How to make GPS function work?

I'm new at Eclipse and the Android applications making so here comes a very rookie question. How can I make this function work properly? I have just copy > paste it to my public class nowActivity extends Activity { and fixed the errors that accord. The function is as follows:
package weather.right;
import weather.right.now.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class nowActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
public void goToSo(View view) {
goToUrl("http://erik-edgren.nu/weather");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Thanks in advance.
protected void onCreate1(Bundle savedInstanceState) should be protected void onCreate(Bundle savedInstanceState)?
You are supposed to override the onCreate() method. See this for more details.
For Android, sub-classes of Activity are supposed to implement certain methods so to do this you have to override certain methods by matching the parent class' methods exactly. onCreate() is one such method.
For the emulator, GPS can be tested by following the guide here. Otherwise it will show up as disabled.

Categories

Resources