I need to create intent from thread:
final Runnable installapps = new Runnable() {
public void run() {
String[] fnames = appsPath.list();
for (String curfile : fnames) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)),
"application/vnd.android.package-archive");
startActivity(intent);
}
}
};
I tried using runOnUiThread but it's still cant be done (app crashed).
Thanks
You need to start the new Intent from within an Activity class. Then simply invoke:
Intent intent = new Intent(this);
Made it with a handler and StartActivityForResult(). It starts installation Intent, waits for any result (just closing of intent), and executes next one.
handler.sendEmptyMessage(0);
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
appcounter++;
if (appcounter < fnames.length) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(appsPath + "/" + fnames[appcounter])), "application/vnd.android.package-archive");
startActivityForResult(intent, req);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// appcounter++;
handler.sendEmptyMessage(0);
}
Related
I have 3 classes: MainActivity, HighScoreActivity, and GameScreenActivity. I want to go to the GameScreenActivity via MainActivity, and then when the game has finished, pass the score to the HighScoreActivity. Everything gets passed to the GameScreenActivity successfully, but it doesn't go to the onActivityResult in HighScoreActivity.
I believe it's because of the MainActivity having the startActivityForResult, so the GameScreenActivity's finishQuiz() is expecting to return its data to the MainActivity. How would I pass the GameScreenActivity's data to the HighScoreActivity?
MainActivity()
MainActivity(){
...
private void startQuiz() {
String difficulty = spinnerDifficulty.getSelectedItem().toString();
Intent intent = new Intent(getBaseContext(), GameScreenActivity.class);
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
}
GameScreenActivity()
GameScreenActivity(){
...
private void finishQuiz(){
Intent resultIntent = new Intent(getBaseContext(),
HighScoreActivity.class);
resultIntent.putExtra(EXTRA_SCORE, score);
resultIntent.putExtra(EXTRA_DIFFICULTY, difficulty);
setResult(RESULT_OK, resultIntent);
startActivity(resultIntent);
}
}
HighScoreActivity()
HighScoreActivity(){
...
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
}
-------------------------------------------------------------
Trying with the Broadcast method:
GameScreenActivity() with broadcasting methods
GameScreenActivity(){
...
private void finishQuiz(){
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("scoreEvent");
intent.putExtra(EXTRA_DIFFICULTY, difficulty);
intent.putExtra(EXTRA_SCORE, score);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
sendBroadcast(intent);
Intent goToHighScores = new Intent(getBaseContext(), HighScoreActivity.class);
startActivity(goToHighScores);
}
}
HighScoreActivity() with broadcasting methods
HighScoreActivity(){
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("scoreEvent"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_QUIZ){
if (resultCode == RESULT_OK) {
int score = data.getIntExtra(GameScreenActivity.EXTRA_SCORE, 0);
String difficulty = data.getStringExtra(GameScreenActivity.EXTRA_DIFFICULTY);
if (score > highScore10) {
updateHighscore(score, difficulty);
}
}
}
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
}
Considering HighScoreActivity is running,
You can utilize LocalBroadcastManager to register local broadcastReceiver in HighScoreActivity with IntentFilter. Also, don't forget to unregister in onDestroy()
Now, instead of setResult do sendBroadcast() from GameScreenActivity
Hope this helps. Happy coding!
My android app has three buttons On click all the button do the same work,
And the code is so long I don't want to copy the code 3 time.
So, how can I do this using a method?
This the code of one button
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
You can try the below code. I have created a public method doSomething() which is called on each button click so it performs the same function whenever it is called.
public void onClick(View v) {
switch (v.getId()) {
case R.id.Btn1:
doSomething();
break;
case R.id.Btn2:
doSomething();
break;
}
}
public void doSomething(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1); //Gallery acessing
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
super.setContentView(R.layout.activity_view);
selectedImage = (ImageView) findViewById(R.id.selectedImage); //Onresult redarct to anothr activity
}
Uri photoUri = data.getData();
if (photoUri != null) {
try {
currentImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
selectedImage.setImageBitmap(currentImage);
} catch (Exception e) {
e.printStackTrace();
Intent myIntent = new Intent(this, ViewActivity.class);
startActivity(myIntent); //switch activity
}
}}
}
private View.OnClickListener myClickListener = new View.OnClickListener(){
public void onClick(View view){
//do all the work here
}
}
then set it in you Views
view1.setOnClickListener(myClickListener);
view2.setOnClickListener(myClickListener);
//... etc
You can Use performClick of first button in other views click.
Button button1 = findViewById(R.id.Btn1)
case R.id.Btn2:
button1.performClick()
I have a method that takes a picture and then in the onActivityResult passes to another activity for subsequent analysis of the picture. So far so good.
My problem is that when I use a handler to repeat the process every 10 sec, the method is called but it will only take photos automatically without passing to the other activity. My guess is that when the method is called again automatically the onActivityResult is never called. Does anybody have a clue of which could may be be the problem?
takePhotoBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
TakePhoto();
}
});
private void TakePhoto() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagepath = new File(getFilesDir(), "images");
File newFile = new File(imagepath, ".jpg");
if (newFile.exists()) {
newFile.delete();
}else {
newFile.getParentFile().mkdir();
}
selectedPhotoPath = getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", newFile);
startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(selectedPhotoPath);
bundle = new Bundle();
bundle.putParcelable(KEY_BITMAP, selectedPhotoPath);
}catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
Intent intent = new Intent(this, Activity.class);
intent.putExtras(bundle);
startActivity(intent);
handler.postDelayed(new Runnable() {
#Override
public void run() {
TakePhoto();
handler.postDelayed(this, 10000);
}
},10000);
}
Any kind of help will be highly appreciated!!! Thanks
I have a 2 activity A and B .
In activity A I start activity B . On activity B I want to do photo and go back to activity A and do next step.
In activity A I have :
Intent intent1 = new Intent(this, CameraActivity.class);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent1, REQUEST_CAMERA);
In activity B I have
buttonClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
camera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
startActivity();
}
});
}
});
private void startActivity(){
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(REQUEST_CAMERA, output);
finish();
}
And on Activity A I have :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
}
I don't know how on Activity B put fileUri and start good method on activity A
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new ImageTask().execute(data);
clearCamera();
}
};
Intent output = new Intent();
output.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
setResult(RESULT_OK, output);//change this
finish();
I have an activity called CForm. I would like to call CGForm for result. After i get the result start another activity. The problem is that when i start the details_click method , it executes the CGFORM, but doesn't waits for setting the result in the form, it jumps to the CDFORM.
here is the code for CFORM:
////////////////////////////CForm/////////////////////////
public boolean details_click()
{
if(listview.getCheckedItemPosition()>=0)
{
ArrayList<ComandaClass> listcompos = CClass.C();
int gestiuneId = 0;
if ((configurare.bAlCom) && (listcompos.size() == 0))
{
StocClass.setComandaContextForDB(this);
listGest = StocClass.Gestiuni_Get();
if (listGest.size() > 1)
{
Intent intent = new Intent();
intent.setClass(CForm.this,CGForm.class);
startActivityForResult(intent,GET_CODE);//here i would like to get back the result from CGForm
dGeid=getGIdResult;
}
}
boolean tof = true;
if ((configurare.bGCom) && (gestiuneId == -1))
tof = false;
if (tof)
{
dCid=listCom.get(listview.getCheckedItemPosition()).getCId();
dClid=listCom.get(listview.getCheckedItemPosition()).getClId();
dF=listCom.get(listview.getCheckedItemPosition()).getF();
Intent intent = new Intent();
intent.setClass(CForm.this,CDForm.class);
startActivity(intent);
}
return true;
}
else
{
Toast.makeText(this, "X", 5000).show();
return false;
}
}
public static int getGIdResult=-1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == GET_CODE)
{
if (resultCode == RESULT_OK)
{
getGIdResult=data.getIntExtra("GIdResult",-1);
}
else
{
getGIdResult=-1;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CGFORM code:
////////////////////CGForm//////////////////
public class CGForm extends Activity
{
public static ArrayList<StocClass> listG=null;
public static int gid;
ListView listview=null;
Button btnOK=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.comenzigestiuni);
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
listview=(ListView)findViewById(R.id.listViewDG);
listG = CForm.listGest;
CG_Load();
}//oncreate
private void CG_Load()
{
//..adding data to listview
btnOK=(Button)findViewById(R.id.menuItemOk);
btnOK.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (listview.getCheckedItemPosition() >= 0)
{
gestiuneid = listG.get(listview.getCheckedItemPosition()).getGId();
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
finish();
}
}
});
}//CG_Load
#Override
protected void onStop()
{
gestiuneid=-1;
Intent intent = new Intent();
intent.putExtra("GIdResult", gestiuneid);
setResult(RESULT_OK, intent);
super.onStop();
}
}
thanks advanced !
Neither startActivity() nor startActivityForResult() are blocking calls. Anything that is supposed to be done after you receive the result needs to move to your onActivityResult() method.