[GUIDE][NOOB Friendly][HOW-TO]Simple Calculator App - Android Software Development

HOW-To Make A Simple Android Calculator​
How To Make A Simple Calculator
Step 1
. Select Create New Android Application
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Creating XML For Layout
To create a calculator first we need to create the layout of the calculator.
Layout is created using XML file given below
Copy This To Your “activity_main” (Note- If you named the layout activity main or something else please change it to activity_main or it will give a couple of errors)
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/result_id"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<Button
android:id="@+id/Btn7_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:text="7"
android:onClick="btn7Clicked"
/>
<Button
android:id="@+id/Btn8_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn7_id"
android:text="8"
android:onClick="btn8Clicked"
/>
<Button
android:id="@+id/Btn9_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn8_id"
android:text="9"
android:onClick="btn9Clicked"
/>
<Button
android:id="@+id/Btnclear_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn9_id"
android:text="clear"
android:onClick="btnclearClicked"
/>
<Button
android:id="@+id/Btn4_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn7_id"
android:text="4"
android:onClick="btn4Clicked"
/> <Button
android:id="@+id/Btn5_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn8_id"
android:layout_toRightOf="@id/Btn4_id"
android:text="5"
android:onClick="btn5Clicked"
/> <Button
android:id="@+id/Btn6_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn9_id"
android:layout_toRightOf="@id/Btn5_id"
android:text="6"
android:onClick="btn6Clicked"
/>
<Button
android:id="@+id/Btnplus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnclear_id"
android:layout_toRightOf="@id/Btn6_id"
android:text="+"
android:onClick="btnplusClicked"
/>
<Button
android:id="@+id/Btn1_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn4_id"
android:text="1"
android:onClick="btn1Clicked"
/>
<Button
android:id="@+id/Btn2_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn5_id"
android:layout_toRightOf="@id/Btn1_id"
android:text="2"
android:onClick="btn2Clicked"
/>
<Button
android:id="@+id/Btn3_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn6_id"
android:layout_toRightOf="@id/Btn2_id"
android:text="3"
android:onClick="btn3Clicked"
/>
<Button
android:id="@+id/Btnminus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnplus_id"
android:layout_toRightOf="@id/Btn3_id"
android:text="-"
android:onClick="btnminusClicked"
/>
<Button
android:id="@+id/Btnequal_id"
android:layout_width="110dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:text="="
android:onClick="btnequalClicked"
/>
<Button
android:id="@+id/Btndivide_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:layout_toRightOf="@id/Btnequal_id"
android:text="/"
android:onClick="btndivideClicked"
/>
<Button
android:id="@+id/Btnmulti_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnminus_id"
android:layout_toRightOf="@id/Btndivide_id"
android:text="*"
android:onClick="btnmultiClicked"
/>
</RelativeLayout>
The Graphical Layout Will look Like this
Then You have to Make The Buttons work and calculate your numbers
Simply find your MainActivity.java (It Is place under package name)
Copy This to your java file :
Code:
package com.dc.simplecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public String str ="";
Character op = 'q';
int i,num,numtemp;
EditText showResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showResult = (EditText)findViewById(R.id.result_id);
}
public void btn1Clicked(View v){
insert(1);
}
public void btn2Clicked(View v){
insert(2);
}
public void btn3Clicked(View v){
insert(3);
}
public void btn4Clicked(View v){
insert(4);
}
public void btn5Clicked(View v){
insert(5);
}
public void btn6Clicked(View v){
insert(6);
}
public void btn7Clicked(View v){
insert(7);
}
public void btn8Clicked(View v){
insert(8);
}
public void btn9Clicked(View v){
insert(9);
}
public void btnplusClicked(View v){
perform();
op = '+';
}
public void btnminusClicked(View v){
perform();
op = '-';
}
public void btndivideClicked(View v){
perform();
op = '/';
}
public void btnmultiClicked(View v){
perform();
op = '*';
}
public void btnequalClicked(View v){
calculate();
}
public void btnclearClicked(View v){
reset();
}
private void reset() {
// TODO Auto-generated method stub
str ="";
op ='q';
num = 0;
numtemp = 0;
showResult.setText("");
}
private void insert(int j) {
// TODO Auto-generated method stub
str = str+Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str);
}
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num;
}
private void calculate() {
// TODO Auto-generated method stub
if(op == '+')
num = numtemp+num;
else if(op == '-')
num = numtemp-num;
else if(op == '/')
num = numtemp/num;
else if(op == '*')
num = numtemp*num;
showResult.setText(""+num);
}
}
Next Step!
Testing Your App, Fingers Crossed
Simply Click On Run>Run As Android Application
Congo! You Just Made A Simple Calc App……
Exporting Your App
Open Android Manifest.xml
Select use Export Wizard
That’s All….
If you have any queries post in this thread I will try my best to solve it…
Sucess!
Have A Good Day!
​

Reserved

Related

[Q] App that start when boot of the phone is complete

Hi boys,
I'm a novice android programmer.
I want to create an app that start when the boot of the phone is complete.
I've write this code, the application work if I click on the icon, but it don't work when the boot of the phone is complete!!
this is my code:
Code:
public class HelloMyBoss extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private String sayd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sayd="";
tts= new TextToSpeech(this, this);
}
@Override
protected void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS) {
// Set preferred language
int result = tts.setLanguage(Locale.ITALY);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Lanuage data is missing or the language is not supported.
Log.e(TAG, "Language is not available.");
} else {
sayHello();
}
} else {
// Initialization failed.
/Log.e(TAG, "Could not initialize TextToSpeech.");
}
}
private void sayHello() {
String hello = "Buon Giorno! Mi sono appena acceso...";
tts.speak(hello,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
}
Code:
public class MyIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent arg1) {
Intent startupBootIntent = new Intent(context, HelloMyBoss.class);
startupBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupBootIntent);
}
}
...and this is my manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mrbrown.android.hellomyboss"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloMyBoss"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="4"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Why it don't work?? What's my error???
Help me please!!

2.3.3 to 4.2.2 Http Get - Help me conquer learning curve

Hey all!
New to Android but not developing. App runs great with emulator running Android 2.3.3. When I install the app to my phone (Samsung Galaxy 4S Active) runnnig Android 4.2.2, the Http Get execute command on the client does not seem to happen. I get no data back reported to my TextView.
I know there is some learning curve I'm missing here, and would appreciate some guidance.
HttpExample.java
Code:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodEx test = new GetMethodEx();
try {
String returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetMethodEx.java
Code:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GetMethodEx {
public String getInternetData () throws Exception {
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("CANTPOSTURL");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally {
if (in !=null) {
try {
in.close();
return data;
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="CANTPOSTURL"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.HttpExample"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
httpex.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="CANTPOSTURL"
xmlns:tools="CANTPOSTURL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HttpActivity">
<ScrollView android:layout_height="fill_parent" android:layout_width="fill_parent">
<TextView
android:id="@+id/tvHttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading Data" >
</TextView>
</ScrollView>
</LinearLayout>
I would post the logcat but there really is no issue at 2.3.3... just need to know what i'm missing going to 4.2.2.
Thanks in advance, I know this should be easy for you all.

[Tutorial] Learn to create a BMI Calculator for Android

Hello,
I create that thread to present you a tutorial aiming to learn you how to create a Body Mass Index Calculator for Android. This tutorial is ideal for beginners that want to discover how to create a first application. You can discover the tutorial in video on Youtube :
Create a Body Mass Index Calculator for Android
The Body Mass Index (BMI) or Quetelet index is a value derived from the mass weight and height of an individual. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed in units of kg/m². By analyzing the BMI value, we can determine a diagnostic. First step for the application is to define a layout letting users to enter weight and height values to calculate the BMI index. Besides, we will need a button to launch the BMI calculation and also a TextView to display the result.
The layout will have the following form :
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.ssaurel.bmicalculator.MainActivity">
<TextView
android:text="@string/weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginTop="50dp"
android:textSize="20sp"/>
<EditText
android:id="@+id/weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:ems="6"
android:inputType="number|numberDecimal"
android:textSize="20sp"/>
<TextView
android:text="@string/height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginTop="50dp"
android:textSize="20sp"/>
<EditText
android:id="@+id/height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:ems="6"
android:inputType="number|numberDecimal"
android:textSize="20sp"/>
<Button
android:id="@+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="25dp"
android:onClick="calculateBMI"
android:text="@string/calculateBMI"
/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginTop="25dp"
android:textSize="20sp"/>
</LinearLayout>
Now, we can write the Java code in our Main Activity :
Code:
package com.ssaurel.bmicalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText height;
private EditText weight;
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
result = (TextView) findViewById(R.id.result);
}
public void calculateBMI(View v) {
String heightStr = height.getText().toString();
String weightStr = weight.getText().toString();
if (heightStr != null && !"".equals(heightStr)
&& weightStr != null && !"".equals(weightStr)) {
float heightValue = Float.parseFloat(heightStr) / 100;
float weightValue = Float.parseFloat(weightStr);
float bmi = weightValue / (heightValue * heightValue);
displayBMI(bmi);
}
}
private void displayBMI(float bmi) {
String bmiLabel = "";
if (Float.compare(bmi, 15f) <= 0) {
bmiLabel = getString(R.string.very_severely_underweight);
} else if (Float.compare(bmi, 15f) > 0 && Float.compare(bmi, 16f) <= 0) {
bmiLabel = getString(R.string.severely_underweight);
} else if (Float.compare(bmi, 16f) > 0 && Float.compare(bmi, 18.5f) <= 0) {
bmiLabel = getString(R.string.underweight);
} else if (Float.compare(bmi, 18.5f) > 0 && Float.compare(bmi, 25f) <= 0) {
bmiLabel = getString(R.string.normal);
} else if (Float.compare(bmi, 25f) > 0 && Float.compare(bmi, 30f) <= 0) {
bmiLabel = getString(R.string.overweight);
} else if (Float.compare(bmi, 30f) > 0 && Float.compare(bmi, 35f) <= 0) {
bmiLabel = getString(R.string.obese_class_i);
} else if (Float.compare(bmi, 35f) > 0 && Float.compare(bmi, 40f) <= 0) {
bmiLabel = getString(R.string.obese_class_ii);
} else {
bmiLabel = getString(R.string.obese_class_iii);
}
bmiLabel = bmi + "\n\n" + bmiLabel;
result.setText(bmiLabel);
}
}
When a user click on the calculate BMI button, the calculateBMI method is called. We get the values entered by the user for the weight and the height. The height is entered in centimeter. For the formula, we need to have a height in meter. So, we divide the value entered by 100. Then, we apply the formula to calculate the BMI :
float bmi = weightValue / (heightValue * heightValue);
With the BMI value, we can display the result on the user interface. We define the displayBMI method for that. To determine the diagnostic associated to the BMI value, we are going to use the following table :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The last step is just to display the BMI value and the diagnostic in the result TextView. After that, you can try the application and enjoy the BMI Calculator in action :
Don't hesitate to try this tutorial and give me your feedbacks.
Thanks.
Sylvain
Hello,
Some users asked me to publish the BMI Calculator Application made in the tutorial.
I made some UI refinements and I published the BMI Calculator on the Google Play Store : https://play.google.com/store/apps/details?id=com.ssaurel.bmicalculator
Don't hesitate to give it a try and give me your feedbacks.
Sylvain

Record Movie in Background

Hallo,
i would to like to record a movie in a Service but it faild and I have no idea.
Thank you for help.
Manifest File
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.mm.googlefit">
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="@mipmap/google_fit"
android:label="@string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
android:excludeFromRecents="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartService"
android:screenOrientation="portrait"
android:excludeFromRecents="true"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".CamcorderReciver" android:exported="false"/>
</application>
</manifest>
In the MainActivity I create a shortcut.
Code:
private void ShortcutIcon(){
Intent shortcutIntent = new Intent(getApplicationContext(), StartService.class);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.google_fit));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
After I cklick on the shourtcout that will start this Activity and this start a Service.
Code:
public class StartService extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, CamcorderReciver.class);
startService(intent);
finish();
}
}
This code start a Service and the Service start the MediaRecoder
Code:
public class CamcorderReciver extends Service {
private static final String TAG = "MediaService";
private boolean isRunning = false;
@Override
public void onCreate() {
Log.e(TAG, "Service onCreate");
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "Service onStartCommand");
Thread thread = new Thread() {
@Override
public void run() {
try {
MediaRecorder.MediaRecoderStartStop();
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
Log.e(TAG, "Service onBind");
return null;
}
@Override
public void onDestroy() {
isRunning = false;
Log.e(TAG, "Service onDestroy");
}
}
This Class would be like to record the movie but it failed on the mediaRecorder.start() Methode.
Code:
public class MediaRecorder {
private static Camera myCamera;
private static android.media.MediaRecorder mediaRecorder;
private static String filenameDate =null;
private static boolean recording;
public static void MediaRecoderStartStop(){
Log.e("MediaRecoderStartStop", "STARTET");
if(recording){
try {
Log.e("IF", "IF");
mediaRecorder.stop();
releaseMediaRecorder();
recording = false;
if (filenameDate != null) {
File file = new File(Environment.getExternalStorageDirectory() + "/WhatsApp/Archiv/" + filenameDate + ".mp4");
if (file.exists()) {
File file2 = new File(Environment.getExternalStorageDirectory() + "/WhatsApp/Archiv/" + filenameDate + ".log4");
file.renameTo(file2);
}
}
}
catch (Exception e){
Log.e("mediaRecorder.start()", e.getMessage());
}
}else{
try {
Log.e("ELSE", "ELSE");
releaseCamera();
Log.e("RELASE-F", "RELASE-F");
prepareMediaRecorder();
Log.e("PREP-F", "PREP-P");
mediaRecorder.start();
Log.e("START-P", "START-P");
}catch (Exception e){
Log.e("mediaRecorder.start()", Log.getStackTraceString(new Exception()));
}
recording = true;
}
}
private static void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
// myCamera.lock();
}
}
private static boolean prepareMediaRecorder(){
try {
if(mediaRecorder == null)
mediaRecorder = new android.media.MediaRecorder();
DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
String date = df.format(Calendar.getInstance().getTime());
filenameDate = date;
if(myCamera == null) {
myCamera = Camera.open();
Camera.Parameters parameters = myCamera.getParameters();
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
myCamera.setParameters(parameters);
myCamera.setDisplayOrientation(90);
myCamera.unlock();
}
mediaRecorder.setCamera(myCamera);
mediaRecorder.setOrientationHint(90);
mediaRecorder.setAudioSource(android.media.MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(android.media.MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(android.media.MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoSize(1280, 720);
mediaRecorder.setVideoFrameRate(60);
mediaRecorder.setVideoEncoder(android.media.MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoEncodingBitRate(3000000);
mediaRecorder.setAudioEncoder(android.media.MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory() + "/WhatsApp/Archiv/"+date+".mp4");
}
catch (Exception e ){
Log.e("prepareMediaRecorder",""+ e.getMessage());
e.printStackTrace();
}
try {
mediaRecorder.prepare();
}
catch (Exception e ){
Log.e("mediaRecorder.prepare()", e.getMessage());
}
return true;
}
private static void releaseCamera(){
if (myCamera != null){
myCamera.release();
myCamera = null;
}
}
}
Hello!
The Application is closing?
What is the Log output?
onlyOne2016 said:
Hello!
The Application is closing?
What is the Log output?
Click to expand...
Click to collapse
Yes the main Application is closed, but i start a Service about a shourt cut and this record the movie.
Nothing in the log

can't send message from wear to my phone app

I want to send data from my wear to the phone app.
I've created a phone app with this AndroidManifest.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.car">
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service android:name=".services.ListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<!-- <data android:scheme="wear" android:host="*" android:pathPrefix="/updatecar" /> -->
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
my Phone ListenerService:
Code:
package sh.evolutio.car.services;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
public class ListenerService extends WearableListenerService {
private static final String TAG = "ListenerService";
private static final String MESSAGE_PATH = "/updatecar";
@Override
public void onCreate() {
Log.d(TAG, "ListenerService created");
}
@Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d(TAG, "onMessageReceived");
if (messageEvent.getPath().equals(MESSAGE_PATH)) {
Log.d(TAG, "good message");
} else {
Log.d(TAG, "bad message");
}
}
}
my MainActivity with this onCreate:
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startService(new Intent(MainActivity.this, ListenerService.class));
}
When I start the App on my phone I got in the Logcat:
Code:
26131-26131/sh.evolutio.car D/ListenerService: ListenerService created
When I send with the wearapp some data to my phone, my ListenerService didn't fire the onMessageReceived method..
Here is my AndroidManifest from the wearapp:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sh.evolutio.carwear">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.DeviceDefault">
<uses-library
android:name="com.google.android.wearable"
android:required="true" />
<meta-data
android:name="com.google.android.wearable.standalone"
android:value="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The MainActivity from the wearapp looks like this:
Code:
package sh.evolutio.carwear;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static String TAG = "MainActivity";
private static final String MESSAGE_PATH = "/updatecar";
Node mNode; // the connected device to send the message to
GoogleApiClient mGoogleApiClient;
private boolean mResolvingError = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Connect the GoogleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
sendMessage("test");
// Enables Always-on
setAmbientEnabled();
}
@Override
protected void onStart() {
super.onStart();
if (!mResolvingError) {
mGoogleApiClient.connect();
}
}
/**
* Resolve the node = the connected device to send the message to
*/
private void resolveNode() {
Log.d(TAG, "resolveNode");
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient)
.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
@Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
Log.d(TAG, "resolvedNode: " + node);
mNode = node;
}
}
});
}
@Override
public void onConnected(Bundle bundle) {
resolveNode();
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "connectionResult: " + connectionResult);
}
/**
* Send message to mobile handheld
*/
private void sendMessage(String Key) {
if (mNode != null && mGoogleApiClient!= null && mGoogleApiClient.isConnected()) {
final String messageKey = Key;
Log.d(TAG, "isConnected: " + mGoogleApiClient.isConnected());
Log.d(TAG, "connected to: " + mNode.getId());
Task<Integer> sendTask = Wearable.getMessageClient(MainActivity.this).sendMessage(mNode.getId(), MESSAGE_PATH, messageKey.getBytes());
sendTask.addOnSuccessListener(new OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.d(TAG, "onSuccess: " + integer);
}
});
sendTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
});
Wearable.MessageApi.sendMessage(mGoogleApiClient, mNode.getId(), MESSAGE_PATH, messageKey.getBytes()).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
@Override
public void onResult(@NonNull MessageApi.SendMessageResult sendMessageResult) {
if (sendMessageResult.getStatus().isSuccess()) {
Log.v(TAG, "Message: { " + messageKey + " } sent to: " + mNode.getDisplayName());
} else {
// Log an error
Log.v(TAG, "ERROR: failed to send Message");
}
}
}
);
}
}
}
When I the message got send, i got this in the logcat from the wearapp:
Code:
sh.evolutio.carwear D/MainActivity: isConnected: true
sh.evolutio.carwear D/MainActivity: connected to: 778d0d53
sh.evolutio.carwear V/MainActivity: Message: { forward } sent to: HUAWEI Mate 10 Pro
sh.evolutio.carwear D/MainActivity: onSuccess: 17282
so the message was sent to my Mate 10 Pro. But why my Mate 10 Pro App can't receive the Message?

Categories

Resources