Issues Passing String Data Between Two Classes - java

I need to share certain strings with my service class however when I attempt to do so I'm getting two errors stating "myWifiInfo cannot be resolved" when attempting to implement a string array using the following method (shown in the source below - and the link below):
Passing String array between two class in android application
Any suggestions? (I've been trying very hard to pass this data to a server I have running - I feel like I'm almost there - I just can't figure out why the service class can't find the strings from Main.java)
Main.java:
Intent intent = new Intent(Main.this, Service_class.class);
String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
intent.putExtra("strings", myStrings);
startActivity(intent);
Service_class.java:
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
Main.java Full Source Code:
import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class Main extends Activity {
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
intent.putExtra("strings", myStrings);
startActivity(intent);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
12 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
ParseAnalytics.trackAppOpened(getIntent());
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
};
};}
Service Class Full Source Code:
import com.parse.ParseObject;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;
public class Service_class extends Service {
public static String TAG="TEST TAG";
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int speed) {
// TODO Auto-generated method stub
return null;
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private Chronometer findViewById(int chronometer) {
// TODO Auto-generated method stub
return null;
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}}};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
// Log.d(TAG, "starting service");
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}

btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);
intent.putExtra("strings", myStrings);
startActivity(intent);
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);
intent.putExtra("strings", myStrings);
startActivity(intent);
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
try this...myStrings Declare Globally And delcare intent And Put value Line write in button Click Event.

myWifiInfo isn't declared/ visible from where you use it. Instantiate it with WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); as you do above in your run() method.
Just because you already declared myWifiInfo somewhere in your code doesn't mean you can use it anywhere. The declaration of myWifiInfo isn't visible from the run method. It's called 'scope'.
So change this:
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
to
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));

When you write new Runnable(){...} you are instantiating an inline class; insede this class this refers to the class itself. You are referring to this.myWifiReceiver but I don't see where the myWifiReceiver object is declared.

Related

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.

How to make an android app show notification even when it is closed

I want to make an app that shows a notification as soon as headphone is plugged in and remove it when it is plugged out. My app works fine when it is on or home button is pressed, but doesn't work when back is pressed or app is closed by long pressing home and swiping it away. What should I use in order to make it work?
This is my code
package com.example.earphone;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class HeadsetPlugReceiver extends BroadcastReceiver {
TextView t1;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}
boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
// boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");
Log.v("message", "headphone connected" + headsetName);
Intent i = new Intent(context, MainActivity.class);
PendingIntent p = PendingIntent.getActivity(context,0,i,0);
// Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if(state==1){
Intent intent1 = new Intent(context, ES.class);
context.startForegroundService(intent1);
}
switch (state) {
case 0:
Intent intent1 = new Intent(context, ES.class);
context.stopService( intent1);
Toast.makeText(context, "Headphone ejected", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "I have no idea what the headset state is", Toast.LENGTH_SHORT).show();
}
}
}}
package com.example.earphone;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String C_ID = "noti";
#Override
public void onCreate() {
super.onCreate();
createnoti();
}
private void createnoti(){
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel(
C_ID,"ex", NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager nm= getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
}
}
package com.example.earphone;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.example.earphone.App.C_ID;
public class ES extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent ni = new Intent(this,HeadsetPlugReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this,0,ni,0);
Notification notification = new NotificationCompat.Builder(this, C_ID)
.setContentTitle("Headphones plugged in")
.setContentText("currently plugged in")
.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pi).build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MainActivity extends AppCompatActivity {
Button b;
HeadsetPlugReceiver headsetPlugReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.b);
// Intent intent = new Intent(this, ES.class);
//startService(intent);
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter i = new IntentFilter();
i.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver,i);
}
}

Android uri not works on on 6.0 above device how to fixed it?

Hello friend i am working mp3 player my Uri uri = Uri.parse("file:///"+song.getGetpath()); works fine on 6.0 device but its not workin 6.0 above device how to fixed using fileprovider i dont know to use how to use fileprovider i am beginner please help here my uri parse code my all audio file is in my phone device
and it return null param cannot be null
Uri uri = Uri.parse("file:///"+song.getGetpath());
here my class code
package music.playerforandroid;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.view.View;
import android.Manifest;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import android.net.Uri;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import static music.playerforandroid.App.CHANNEL_ID_1;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private BroadcastReceiver broadcastReceiver;
private ArrayList<Song> songList;
private ListView songView;
MediaPlayer mediaPlayer;
private MediaSessionCompat mediaSession;
private int currentSongIndex = 0;
Song song;
private SlidingUpPanelLayout slidingLayout;
Context mContext;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000;
private AudioVisualization audioVisualization;
private VisualizerDbmHandler handler;
int postion;
int totalduration;
int totalTime;
SeekBar seekBar;
private Handler mHandler = new Handler();
private NotificationManagerCompat notificationManager;
Uri uri;
ImageView rotate;
private long currentsongLength;
TextView elapsedTimeLabel, remainingTimeLabel;
TextView title, artist;
ImageView playchange;
ImageButton like, notlike, dislike, notdislike, next, pervious, repeat, reaptenable;
ImageButton play, pause, play_main, pause_main, shuffle, shufflenable;
private SlidingUpPanelLayout mLayout;
private boolean isShuffle;
private boolean checked;
private NotificationManagerCompat mNotificationManagerCompat;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = findViewById(R.id.song_list);
songList = new ArrayList<Song>();
artist = findViewById(R.id.artist);
title = findViewById(R.id.songname);
elapsedTimeLabel = findViewById(R.id.songtime);
remainingTimeLabel = findViewById(R.id.endTime);
seekBar = findViewById(R.id.seekBar3);
next = findViewById(R.id.next);
pervious = findViewById(R.id.pervious);
like = findViewById(R.id.imageButton2);
notlike = findViewById(R.id.imageButton2new);
dislike = findViewById(R.id.button);
notdislike = findViewById(R.id.buttontwo);
play = findViewById(R.id.play_button);
repeat = findViewById(R.id.repeat);
reaptenable = findViewById(R.id.repeatenable);
pause = findViewById(R.id.pause_button);
play_main = findViewById(R.id.play_button_main);
pause_main = findViewById(R.id.pause_button_main);
like = findViewById(R.id.imageButton2);
notlike = findViewById(R.id.imageButton2new);
dislike = findViewById(R.id.button);
notdislike = findViewById(R.id.buttontwo);
play = findViewById(R.id.play_button);
pause = findViewById(R.id.pause_button);
shuffle = findViewById(R.id.shuffle);
shufflenable = findViewById(R.id.shufflenable);
elapsedTimeLabel = findViewById(R.id.endTime);
remainingTimeLabel = findViewById(R.id.songtime);
play_main = findViewById(R.id.play_button_main);
pause_main = findViewById(R.id.pause_button_main);
mLayout = findViewById(R.id.activity_main);
rotate = findViewById(R.id.rotate);
audioVisualization = findViewById(R.id.visualizer_view);
seekBar.setOnSeekBarChangeListener(this);
utils = new Utilities();
mNotificationManagerCompat = NotificationManagerCompat.from(this);
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {
play(position);
}
});
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("music.playerforandroid.ACTION_PAUSE_MUSIC")) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
rotate.clearAnimation();
}
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause_main.getVisibility() == View.VISIBLE) {
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
}
} else if (action.equals("music.playerforandroid.ACTION_PLAY_MUSIC")) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play_main.getVisibility() == View.VISIBLE) {
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
} else if (action.equals("music.playerforandroid.NEXT_PLAY_MUSIC")) {
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
} else if (action.equals("music.playerforandroid.PERVIOUS_PLAY_MUSIC")) {
if (currentSongIndex > 0) {
play(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
play(songList.size() - 1);
currentSongIndex = songList.size() - 1;
}
}
}
};
repeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
repeat.setVisibility(View.GONE);
reaptenable.setVisibility(View.VISIBLE);
shuffle.setVisibility(View.VISIBLE);
shufflenable.setVisibility(View.GONE);
isShuffle = false;
checked = true;
Toast.makeText(getApplicationContext(), "Repeat ON", Toast.LENGTH_SHORT).show();
}
});
reaptenable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
repeat.setVisibility(View.VISIBLE);
reaptenable.setVisibility(View.GONE);
checked = false;
Toast.makeText(getApplicationContext(), "Repeat OFF", Toast.LENGTH_SHORT).show();
}
});
shuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reaptenable.setVisibility(View.GONE);
repeat.setVisibility(View.VISIBLE);
checked = false;
isShuffle = true;
shuffle.setVisibility(View.GONE);
shufflenable.setVisibility(View.VISIBLE);
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle ON", Toast.LENGTH_SHORT).show();
}
});
shufflenable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
shuffle.setVisibility(View.VISIBLE);
shufflenable.setVisibility(View.GONE);
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle OFF", Toast.LENGTH_SHORT).show();
}
});
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notlike.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "You Like the Song", Toast.LENGTH_SHORT).show();
if (notdislike.getVisibility() == View.VISIBLE) {
notdislike.setVisibility(View.GONE);
}
}
});
notlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notlike.setVisibility(View.GONE);
}
});
dislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notdislike.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "You DisLike the Song", Toast.LENGTH_SHORT).show();
if (notlike.getVisibility() == View.VISIBLE) {
notlike.setVisibility(View.GONE);
}
}
});
notdislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notdislike.setVisibility(View.GONE);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
}
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play_main.getVisibility() == View.VISIBLE) {
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
rotate.clearAnimation();
}
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause_main.getVisibility() == View.VISIBLE) {
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
}
}
});
play_main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
}
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play.getVisibility() == View.VISIBLE) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
});
pervious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentSongIndex > 0) {
play(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
play(songList.size() - 1);
currentSongIndex = songList.size() - 1;
}
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
});
}
});
pause_main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause.getVisibility() == View.VISIBLE) {
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
rotate.clearAnimation();
}
}
});
}
#Override
public void onBackPressed() {
if (mLayout != null &&
(mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED || mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.ANCHORED)) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
super.onBackPressed();
}
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int dataColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisPath = musicCursor.getString(dataColumn);
songList.add(new Song(thisId, thisTitle, thisArtist, thisPath));
}
while (musicCursor.moveToNext());
}
}
public void play(int songindex) {
song = songList.get(songindex);
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//file:///" + song.getGetpath()
// final Uri data = FileProvider.getUriForFile(this, "myprovider", new File(song.getGetpath()));
Toast.makeText(getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("file:///"+song.getGetpath());
mediaPlayer = MediaPlayer.create(mContext, uri);
title.setText(song.getTitle());
artist.setText(song.getArtist());
show();
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(handler);
mediaPlayer.start();
seekBar.setProgress(0); seekBar.setMax(100);
updateProgressBar();
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (checked) {
mediaPlayer.setLooping(true);
mediaPlayer.start();
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
play(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public void forward() {
int currentPosition = mediaPlayer.getCurrentPosition();
// check if seekForward time is lesser than song duration
if (currentPosition + seekForwardTime <= mediaPlayer.getDuration()) {
// forward song
mediaPlayer.seekTo(currentPosition + seekForwardTime);
} else {
// forward to end position
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}
public void backword() {
int currentPosition = mediaPlayer.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if (currentPosition - seekBackwardTime >= 0) {
// forward song
mediaPlayer.seekTo(currentPosition - seekBackwardTime);
} else {
// backward to starting position
mediaPlayer.seekTo(0);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
mediaPlayer.release();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();
}
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mediaPlayer.getDuration();
long currentDuration = mediaPlayer.getCurrentPosition();
// Displaying Total Duration time
remainingTimeLabel.setText("" + utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
elapsedTimeLabel.setText("" + utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
seekBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
#Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("music.playerforandroid.ACTION_PAUSE_MUSIC");
intentFilter.addAction("music.playerforandroid.ACTION_PLAY_MUSIC");
intentFilter.addAction("music.playerforandroid.NEXT_PLAY_MUSIC");
intentFilter.addAction("music.playerforandroid.PERVIOUS_PLAY_MUSIC");
registerReceiver(broadcastReceiver,intentFilter);
}
public void show(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.musicicon);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.ACTION_PAUSE_MUSIC"), 0);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.ACTION_PLAY_MUSIC"), 0);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.NEXT_PLAY_MUSIC"), 0);
PendingIntent perviousPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.PERVIOUS_PLAY_MUSIC"), 0);
Notification channel = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(song.getTitle())
.setContentText(song.getArtist())
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_prev, "prev", perviousPendingIntent)
.addAction(R.drawable.ic_play, "play", playPendingIntent)
.addAction(R.drawable.ic_stat_name, "pause", pausePendingIntent)
.addAction(R.drawable.ic_next, "next", nextPendingIntent)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().
setShowActionsInCompactView(1, 2, 3))
.build();
mNotificationManagerCompat.notify(1, channel);
}
}
Your Context is null.
Try changing
mediaPlayer = MediaPlayer.create(mContext, uri);
to
mediaPlayer = MediaPlayer.create(this, uri);
I had thiss problem before, it happens because MediaPlayer.create(...) method returns null object when failed to create, so you have to keep checking if it's null:
do {
mediaPlayer = MediaPlayer.create(mContext, uri);
} while (mediaPlayer == null);
or use another method: mediaPlayer = new MediaPlayer() ,then setDataSource(...) ,then prepare and start.

Issue with Twitter 4j callback on Android

I have successfully integrated twitter in my app but now I want to open next activity upon successful login.
How do I implement a call back method? i use on Activity result for twitter but it does not gives any error but also its does not works kindly tell me the right way to solve it thanks in advance....
package com.example.android.accenturefeed;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
#SuppressWarnings("ALL")
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
public ProgressDialog pdialog;
public AlertDialog alertDialog;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 1901;
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
static String TWITTER_CONSUMER_KEY = "my_consumer_key";
static String TWITTER_CONSUMER_SECRET = "my_consumer_secret";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button TwitterLoginButton;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for facebook signin
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login_activity);
final LoginActivity thisActivity = this;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// for twitter login
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
TwitterLoginButton = (Button) findViewById(R.id.btnLoginTwitter);
TwitterLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
LoginActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
});
// for google signin
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// for logging out from facebook
LoginManager.getInstance().logOut();
// checks internet
if (isNetworkAvailable()==true){
//linkedin button
Button libutton=(Button)findViewById(R.id.btnLinkedin);
libutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//linkedin signin
LISessionManager.getInstance(getApplicationContext()).init(thisActivity, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
#Override
public void onAuthError(LIAuthError error) {
info.setText("Login attempt failed.");
}
}, true);
}
});
// google login button
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
// shows error
info = (TextView)findViewById(R.id.info);
// facebook login button
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
// info.setText(
// "User ID: "
// + loginResult.getAccessToken().getUserId()
// + "\n" +
// "Auth Token: "
// + loginResult.getAccessToken().getToken()
// );
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
Button b1=(Button)findViewById(R.id.loginbutton);
final EditText user =(EditText)findViewById(R.id.editTextentername);
final EditText pass =(EditText)findViewById(R.id.edittextenterpassword);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String givenUsername = user.getText().toString();
String givenPassword = pass.getText().toString();
if (givenUsername.isEmpty() || givenPassword.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setText("Username & password required!");
} else {
pdialog = ProgressDialog.show(LoginActivity.this, "Authenticating", "Please wait...");
sendLoginRequest(givenUsername, givenPassword);
}
}
private void sendLoginRequest(final String givenUsername, final String givenPassword) {
SendLoginRequestAsyncTask asyncTask = (SendLoginRequestAsyncTask) new SendLoginRequestAsyncTask(new SendLoginRequestAsyncTask.AsyncResponse() {
#Override
public void processFinish(String name) {
if (name.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setTextColor(Color.parseColor("#d41a14"));
textView.setText("Username or Password Is Incorrect!");
pdialog.dismiss();
} else {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
intent.putExtra("username", name);
pdialog.dismiss();
startActivity(intent);
}
}
}).execute(givenUsername, givenPassword);
}
}
);
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Check Your Internet Connection");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
private Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// for twitter result
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// for google
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
// for facebook
else {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//forlinkedin
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
}
// for google to open next activity or not
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivityForResult(intent, 1);
} else {
// Signed out, show unauthenticated UI.
info.setText("Login attempt failed.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
// Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
// #Override
// public void onResult(Status status) {
// mGoogleApiClient.disconnect();
// }
// });
return true;
}
return super.onOptionsItemSelected(item);
}
// checks Internet is available or not
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
// for google sign in button on click method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
// google sign in method
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// google connection failed method
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
info.setText("Login attempt failed.");
}
}
remove all the intents from your code except the one from this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Just keep the intent portion in order to go to the next activity in OnActivityResult itself, remove any other intent calls from your entire code and try running the app again.

Issue(s) Null Checking via LogCat - Data Does Not Appear In Log

I'm attempting to find the string or long values in my source code which return data (so I can post them to my server) however when I attempt to null check them using the following:
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
The data never appears in the logs. Any suggestions are greatly appreciated!
SERVICE CLASS SOURCE:
public class Service_class extends Service {
public static String TAG="TEST TAG";
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private TextView findViewById(int speed) {
// TODO Auto-generated method stub
return null;
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private Chronometer findViewById(int chronometer) {
// TODO Auto-generated method stub
return null;
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
Log.d(TAG, String.valueOf(WifiInfo.LINK_SPEED_UNITS));
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}}};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
// Log.d(TAG, "starting service");
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
MAIN.Java
public class Main extends Activity {
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
12 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
ParseAnalytics.trackAppOpened(getIntent());
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
};
};}
you may add one string(any dummy) value so that they will appear, i think
Log.d(TAG,"Null: "+String.valueOf(WifiInfo.LINK_SPEED_UNITS));

Categories

Resources