In the following code of my MainActivity (which downloads a json I need in another activity and shows a loading progress bar), which starts before launching HomeActivity, I get a null object reference error (on the getProgress() method), but HomeActivity then starts anyway if I press back button.
I have searched for this kind of error, but the only solution that seems working is the one that let me starts the HomeActivity after some delay, changing setProgress method like this: (but it seems that the bar doesn't change and I don't think it's a real solution to the problem)
public void setProgress(ProgressBar bar, int progress) {
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if (bar.getProgress() == 100) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
}
}, 4000);
}
}
----------------------------------------------------------------------
package ...
import ...
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView textView;
private OkHttpClient httpClient;
private String url;
private Request request;
private static boolean loaded = false;
private FileInputStream inputStream;
private FileOutputStream outputStream;
private static final String FILE_NAME = "data.txt";
private AlertDialogConnection noResponse;
private AlertDialogConnection noInternet;
private AlertDialogConnection serverError;
private AlertDialogConnection internalError;
public MainActivity(){
this.inputStream = null;
this.outputStream = null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
this.httpClient = new OkHttpClient();
this.url = "my url";
this.request = new Request.Builder().url(url).build();
this.progressBar = findViewById(R.id.progressBar);
this.progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.progressBarColor), android.graphics.PorterDuff.Mode.SRC_IN);
this.textView = findViewById(R.id.textView);
this.noResponse = new AlertDialogConnection();
this.noInternet = new AlertDialogConnection();
this.serverError = new AlertDialogConnection();
this.internalError = new AlertDialogConnection();
checkConnectionStatusAndStart();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public void checkConnectionStatusAndStart(){
if(checkConnectionStatus())
requestData();
else{
this.noInternet.setTitle("no connection!");
this.noInternet.setText("connection error!");
this.noInternet.show(getSupportFragmentManager(), "no connection!");
}
}
public boolean checkConnectionStatus(){
boolean wifiConnection = false;
boolean mobileConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null)
networkInfo = connectivityManager.getActiveNetworkInfo();
if((networkInfo != null) && networkInfo.isConnected()){
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){
/* Wifi On */
wifiConnection = true;
}
if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){
/* Mobile data On */
mobileConnection = true;
}
return (wifiConnection || mobileConnection);
}else{
/* You are not connected */
return false;
}
}
public void requestData(){
textView.setText("waiting server...");
httpClient.connectTimeoutMillis(); //Timeout
httpClient.writeTimeoutMillis();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if(!call.isExecuted()){
Toast.makeText(getApplicationContext(), "server error!", Toast.LENGTH_LONG).show();
}
Log.d("HTTP-Error", "HTTP error!");
AlertDialogConnection errorDialog = new AlertDialogConnection();
errorDialog.setTitle("server error!");
errorDialog.setText("server error, try later");
errorDialog.show(getSupportFragmentManager(), "messaging error!");
}
#Override
public void onResponse(#NotNull Call call, Response response) throws IOException {
if(response.isSuccessful()){
/* HTTP-code: 200 */
final String body = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
((TextView)findViewById(R.id.textView)).setText("Setting of suggestion variables!");
setProgress(progressBar, 10);
try {
JSONObject json = new JSONObject(body);
try {
((TextView)findViewById(R.id.textView)).setText("retrieving server infos!");
saveJSON(json, getApplicationContext());
} catch (FileNotFoundException e) {
Log.d("File Not Found!", "FileNotFoundException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
} catch (IOException e) {
Log.d("File Not Found!", "IOException!");
internalError.setTitle("error while saving data!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "error while saving data!");
e.printStackTrace();
}
setProgress(progressBar, 90);
MainActivity.loaded = true;
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON-Error", "parsing JSON error!");
internalError.setTitle("server error!");
internalError.setText("server error, try later");
internalError.show(getSupportFragmentManager(), "JSON messaging error!");
}
}
});
}else{
/* Http-code: 500 */
Log.d("HTTP-Error", "server error!");
serverError.setTitle("server error!");
serverError.setText("server error");
serverError.show(getSupportFragmentManager(), "server error!");
}
}
});
}
public void setProgress(ProgressBar bar, int progress){
int oldProgress = bar.getProgress();
int totalProgress = oldProgress + progress;
bar.setProgress(totalProgress);
if(bar.getProgress() == 100){
Intent intent = new Intent(this, HomePage.class);
startActivity(intent);
this.onDestroy();
}
}
private void saveJSON(JSONObject json, Context context) throws IOException {
outputStream = null;
try{
outputStream = context.openFileOutput(FILE_NAME, MODE_PRIVATE);
outputStream.write(json.toString().getBytes());
}finally {
if(outputStream != null){
outputStream.close();
}
}
}
public JSONObject loadJSON(Context context) throws IOException, JSONException {
inputStream = context.openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(reader.readLine());
inputStream.close();
return jsonObject;
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
this.httpClient = null;
this.noResponse = null;
this.noInternet = null;
this.serverError = null;
this.internalError = null;
this.request = null;
this.textView = null;
this.progressBar = null;
this.url = null;
super.onDestroy();
}
#Override
protected void onResume() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onResume();
}
#Override
protected void onRestart() {
if(!loaded){
checkConnectionStatusAndStart();
}
super.onRestart();
}
#Override
protected void onPause() {
if(!loaded ){
checkConnectionStatusAndStart();
}
super.onPause();
}
}
Related
I have almost a week figuring out how should I have one instance of exoplayer in background.
I want to use this instance in a playerview and in notification as well. Problem I am facing now, the player plays well, after a time it pauses (to release resource I guess), but when i click play it plays again, when i click other oudio, I get two audio playing at same time.
Here are my codes.
------------------------ BACKGROUND SERVICE --------------------------------------
public class BackgroundPlayingService extends Service {
public static PlayerNotificationManager playerNotificationManager;
public static ExoPlayer exoPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (this.exoPlayer == null){
createPlayer();
}
/////////////////THIS WAS ADDED LATER
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
exoPlayer.pause();
exoPlayer = null;
playerNotificationManager.setPlayer(null);
}
private void createPlayer(){
exoPlayer = new ExoPlayer.Builder(this).build();
MediaItem mediaItem;
try {
mediaItem = MediaItem.fromUri(Uri.parse(DataUtility.playingUrl));
}catch (Exception e){
mediaItem = MediaItem.fromUri(Uri.parse("https://server13.mp3quran.net/husr/062.mp3"));
}
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
exoPlayer.addListener(new Player.Listener() {
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
if (playbackState==Player.STATE_READY){
try {
ThePlayingActivity.downloadBtn.setVisibility(View.VISIBLE);
showNotification();
}catch (Exception ignore){
}
}
if (playbackState == Player.STATE_BUFFERING) {
try {
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
}catch (Exception e){
}
} else {
try {
ThePlayingActivity.myProgress.setVisibility(View.GONE);
}catch (Exception e){
}
}
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
}
#Override
public void onPlayerError(PlaybackException error) {
Player.Listener.super.onPlayerError(error);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();
}
playerNotificationManager.setPlayer(null);
}catch (Exception ignore){
}
}
});
exoPlayer.play();
try {
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
}catch (Exception e){
Log.d("background", "createPlayer: set player to view"+e.getLocalizedMessage());
}
}
public static void setNewPlayeData(){
MediaItem mediaItem = MediaItem.fromUri(Uri.parse(DataUtility.playingUrl));
exoPlayer.setMediaItem(mediaItem);
exoPlayer.prepare();
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
try {
ThePlayingActivity.myPlayerView.setPlayer(exoPlayer);
}catch (Exception e){
Log.d("background", "createPlayer: set player to view"+e.getLocalizedMessage());
}
}
public void showNotification() {
playerNotificationManager = new PlayerNotificationManager.Builder(this, 151,
this.getResources().getString(R.string.app_name))
.setChannelNameResourceId(R.string.app_name)
.setChannelImportance(IMPORTANCE_HIGH)
.setMediaDescriptionAdapter(new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return player.getCurrentMediaItem().mediaMetadata.displayTitle;
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
return null;
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return Objects.requireNonNull(player.getCurrentMediaItem()).mediaMetadata.artist;
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}).setNotificationListener(new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
PlayerNotificationManager.NotificationListener.super.onNotificationPosted(notificationId, notification, ongoing);
}
})
.build();
playerNotificationManager.setUseStopAction(false);
try {
playerNotificationManager.setPlayer(exoPlayer);
}catch (Exception e){
}
}
}
-----------------------HERE IS THE ACTIVITY WITH PLAYER ----------------------------------
public class ThePlayingActivity extends AppCompatActivity {
private static final int PERMISION_STORAGE_CODE = 100;
private ProgressBar downloadingProgress;
public static ProgressBar myProgress;
public static Dialog dialog;
private ConstraintLayout layoutForSnack;
long downloadId;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
String myurl;
public static PlayerControlView myPlayerView;
private TextView currentPlaying, downloadingTv;
public static Button downloadBtn;
private String thePlayingSura;
private final BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
if (downloadId == id){
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
downloadBtn.setText("DOWNLOADED");
downloadBtn.setBackgroundColor(Color.TRANSPARENT);
downloadBtn.setTextColor(Color.BLACK);
downloadBtn.setClickable(false);
Toast.makeText(context, "DOWNLOAD COMPLETED", Toast.LENGTH_SHORT).show();
}
}
};
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_playing);
myPlayerView = findViewById(R.id.playerView);
Intent dataIntent = getIntent();
myurl = dataIntent.getStringExtra("theUrl");
if (BackgroundPlayingService.exoPlayer == null){
startService();}else{
BackgroundPlayingService.setNewPlayeData();
myPlayerView.setPlayer(BackgroundPlayingService.exoPlayer);
}
keepActivityAlive();
registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadingProgress = findViewById(R.id.downloadProgress);
downloadingTv = findViewById(R.id.downloadingWaitTv);
currentPlaying = findViewById(R.id.currentPlaying);
downloadBtn = findViewById(R.id.downloadbtn);
downloadBtn.setVisibility(View.GONE);
myProgress = findViewById(R.id.progressBar2);
myProgress.setVisibility(View.GONE);
layoutForSnack = findViewById(R.id.constraintLayout);
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
thePlayingSura = dataIntent.getStringExtra("sendSuraName");
currentPlaying.setText(thePlayingSura+" - " + DataUtility.theKariName);
/////////////end of ids
showLoadingDialog();
/////////////////download
downloadBtn.setOnClickListener(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//todo ask permission
String permissions[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,PERMISION_STORAGE_CODE);
}else{
downloadStaffs();
}
}else {
//TODO DOWNLOAD
downloadStaffs();
}
});
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
}
#Override
public void onBackPressed() {
super.onBackPressed();
//todo fire service (may be)
}
private void showLoadingDialog() {
dialog = new Dialog(ThePlayingActivity.this);
dialog.setContentView(R.layout.dialog_loading_quran);
dialog.setCancelable(false);
dialog.show();
}
private void showSnackBar() {
Snackbar snackbar = Snackbar.make(layoutForSnack, "THERE WAS ON ERROR, CHECK YOUR INTERNET CONNECTION", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("RETRY", view -> {
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISION_STORAGE_CODE:{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
// we have permission
//todo Download
downloadStaffs();
}else{
Toast.makeText(ThePlayingActivity.this , "PERMISSION DENIED... CAN NOT DOWNLOAD", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
try {
if (wakeLock.isHeld()){
wakeLock.release();}
}catch (Exception ignore){
}
}
private void downloadStaffs(){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DataUtility.playingUrl));
request.setDescription("Download File");
request.setTitle(thePlayingSura);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, thePlayingSura+" - "+ DataUtility.theKariName+".mp3");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
this.downloadId = downloadId;
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.downloadProgress);
downloadingTv.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
#SuppressLint("Range")
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
#SuppressLint("Range") int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
#SuppressLint("Range") int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final double dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
Log.d("MESSAGES", statusMessage(cursor));
cursor.close();
}
}
}).start();
}
#SuppressLint("Range")
private String statusMessage(Cursor c) {
String msg = "???";
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed!";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused!";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending!";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress!";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete!";
break;
default:
msg = "Download is nowhere in sight";
break;
}
return (msg);
}
}
private void keepActivityAlive(){
powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"QuranAudio:WakeLock");
}
private void startService(){
Intent i = new Intent(this, BackgroundPlayingService.class);
startService(i);
}
}
I figured it out.
I had to keep most of my business inside in onStartCommand
public class BackgroundPlayingService extends Service {
public static final String TAG = "bck_service";
public static ExoPlayer player;
public static PlayerNotificationManager playerNotificationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String url = DataUtility.playingUrl;
if (url==null){
url = "https://server8.mp3quran.net/afs/Rewayat-AlDorai-A-n-Al-Kisa-ai/025.mp3";
}
if (player == null){
player = createPlayerIfNull();
MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
player.setMediaItem(mediaItem);
player.prepare();
player.addListener(new Player.Listener() {
#Override
public void onEvents(Player player, Player.Events events) {
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
if (playbackState==Player.STATE_READY){
try {
ThePlayingActivity.downloadBtn.setVisibility(View.VISIBLE);
showNotification();
}catch (Exception ignore){
}
}
if (playbackState == Player.STATE_BUFFERING) {
try {
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
}catch (Exception e){
}
} else {
try {
ThePlayingActivity.myProgress.setVisibility(View.GONE);
}catch (Exception e){
}
}
}
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
}
#Override
public void onPlayerError(PlaybackException error) {
Player.Listener.super.onPlayerError(error);
try {
if (ThePlayingActivity.dialog.isShowing()){
ThePlayingActivity.dialog.dismiss();}
}catch (Exception ignore){
}
}
});
player.play();
try {
ThePlayingActivity.myPlayerView.setPlayer(player);
}catch (Exception ignore){}
}
//notification
createNotificationChannel();
Intent i = new Intent(this,BackgroundPlayingService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,0);
Notification notification = new NotificationCompat.Builder(this,"myChannelId")
.setContentTitle("QURAN IS PLAYING")
.setContentText("This means that Qur-an app is open. You can close it from app exit menu")
.setSmallIcon(androidx.core.R.drawable.notification_icon_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
return START_STICKY;
}
public ExoPlayer createPlayerIfNull() {
if (player == null) {
player = new ExoPlayer.Builder(BackgroundPlayingService.this).build();
ThePlayingActivity.myProgress.setVisibility(View.VISIBLE);
try {
ThePlayingActivity.dialog.show();
}catch (Exception e){
Log.d(TAG, "createPlayerIfNull: ");
}
}
return player;
}
private void createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel("myChannelId","qur-anAudiChannel", NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player = null;
stopForeground(true);
}
public void showNotification() {
playerNotificationManager = new PlayerNotificationManager.Builder(this, 151,
this.getResources().getString(R.string.app_name))
.setChannelNameResourceId(R.string.app_name)
.setChannelImportance(IMPORTANCE_HIGH)
.setMediaDescriptionAdapter(new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return player.getCurrentMediaItem().mediaMetadata.displayTitle;
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
return null;
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return Objects.requireNonNull(player.getCurrentMediaItem()).mediaMetadata.artist;
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
}).setNotificationListener(new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
}
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
PlayerNotificationManager.NotificationListener.super.onNotificationPosted(notificationId, notification, ongoing);
}
})
.build();
playerNotificationManager.setUseStopAction(false);
try {
playerNotificationManager.setPlayer(player);
}catch (Exception e){
}}
}
-------------------- player view activity ------------------------------------
public class ThePlayingActivity extends AppCompatActivity {
private static final int PERMISION_STORAGE_CODE = 100;
private ProgressBar downloadingProgress;
public static ProgressBar myProgress;
public static Dialog dialog;
private ConstraintLayout layoutForSnack;
long downloadId;
private PowerManager powerManager;
private PowerManager.WakeLock wakeLock;
String myurl;
public static PlayerControlView myPlayerView;
private TextView currentPlaying, downloadingTv;
public static Button downloadBtn;
private String thePlayingSura;
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadId == id) {
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
downloadBtn.setText("DOWNLOADED");
downloadBtn.setBackgroundColor(Color.TRANSPARENT);
downloadBtn.setTextColor(Color.BLACK);
downloadBtn.setClickable(false);
Toast.makeText(context, "DOWNLOAD COMPLETED", Toast.LENGTH_SHORT).show();
}
}
};
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_playing);
myPlayerView = findViewById(R.id.playerView);
Intent dataIntent = getIntent();
myurl = dataIntent.getStringExtra("theUrl");
Intent backgroundPlayIntent = new Intent(ThePlayingActivity.this,BackgroundPlayingService.class);
try {
stopService(backgroundPlayIntent);
}catch (Exception e){}
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
startForegroundService(backgroundPlayIntent);
}else{
startService(backgroundPlayIntent);
}
keepActivityAlive();
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadingProgress = findViewById(R.id.downloadProgress);
downloadingTv = findViewById(R.id.downloadingWaitTv);
currentPlaying = findViewById(R.id.currentPlaying);
downloadBtn = findViewById(R.id.downloadbtn);
downloadBtn.setVisibility(View.GONE);
myProgress = findViewById(R.id.progressBar2);
myProgress.setVisibility(View.VISIBLE);
layoutForSnack = findViewById(R.id.constraintLayout);
downloadingProgress.setVisibility(View.GONE);
downloadingTv.setVisibility(View.GONE);
thePlayingSura = dataIntent.getStringExtra("sendSuraName");
currentPlaying.setText(thePlayingSura + " - " + DataUtility.theKariName);
/////////////end of ids
showLoadingDialog();
/////////////////download
downloadBtn.setOnClickListener(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String permissions[] = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISION_STORAGE_CODE);
} else {
downloadStaffs();
}
} else {
downloadStaffs();
}
});
}
private void showLoadingDialog() {
dialog = new Dialog(ThePlayingActivity.this);
dialog.setContentView(R.layout.dialog_loading_quran);
dialog.setCancelable(false);
dialog.show();
}
public void showSnackBar() {
Snackbar snackbar = Snackbar.make(layoutForSnack, "THERE WAS ON ERROR, CHECK YOUR INTERNET CONNECTION", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("RETRY", view -> {
//todo retry player
});
snackbar.setActionTextColor(Color.YELLOW);
snackbar.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISION_STORAGE_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// we have permission
downloadStaffs();
} else {
Toast.makeText(ThePlayingActivity.this, "PERMISSION DENIED... CAN NOT DOWNLOAD", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onDownloadComplete);
try {
if (wakeLock.isHeld()) {
wakeLock.release();
}
} catch (Exception ignore) {
}
}
private void downloadStaffs() {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DataUtility.playingUrl));
request.setDescription("Download File");
request.setTitle(thePlayingSura);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, thePlayingSura + " - " + DataUtility.theKariName + ".mp3");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
this.downloadId = downloadId;
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.downloadProgress);
downloadingTv.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
#SuppressLint("Range")
#Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
#SuppressLint("Range") int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
#SuppressLint("Range") int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final double dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
Log.d("MESSAGES", statusMessage(cursor));
cursor.close();
}
}
}).start();
}
#SuppressLint("Range")
private String statusMessage(Cursor c) {
String msg = "???";
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed!";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused!";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending!";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress!";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete!";
break;
default:
msg = "Download is nowhere in sight";
break;
}
return (msg);
}
private void keepActivityAlive() {
powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "QuranAudio:WakeLock");
}
private void startService() {
Intent i = new Intent(this, BackgroundPlayingService.class);
startService(i);
}}
--------------------- extra --------------------------------------
I also had to create other service to remove notification when the
user kill app by clearing app from recent apps.
here is it
MyAppService extends Service {
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent i = new Intent(MyAppService.this,BackgroundPlayingService.class);
try {
BackgroundPlayingService.playerNotificationManager.setPlayer(null);
stopService(i);
}catch (Exception ignore){}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}}
-------------------- WARNING ----------------------------------
I don't take this as a best approach, but it gave me a quick solution while waiting for a better approach.
I will pot the app link here when it's available in playstore.
Here is the error - java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.wdchat.MainActivity$SendReceive.write(byte[])' on a null object reference.
I have included my mainactivity class code and wifibroadcastreceover class code as well. The code is actually from wifip2p tutorial on youtube made by sarthi technology
Here is my MainActivity class.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
AppCompatEditText editText;
ImageView wifi_on_off_iv, wifi_descovery_iv, send_btn_iv, save_ic_iv, brd_msg_iv;
TextView username, sentMessage, connectionStatus, tallytext, tallyno;
WifiManager wifiManager;
WifiP2pManager p2pManager;
WifiP2pManager.Channel mchannel;
String messageText;
LinearLayout nestedLinearlayout;
ListView listView;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
BroadcastReceiver broadcastReceiver;
IntentFilter intentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] devicenameArray;
WifiP2pDevice[] wifiP2pDeviceArray;
static final int MESSAGE_READ = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
switch (message.what){
case MESSAGE_READ:
byte[] readBuff = (byte[]) message.obj;
String temMsg = new String(readBuff, 0, message.arg1);
sentMessage.setText(temMsg);
break;
}
return true;
}
});
private void exqListener() {
wifi_on_off_iv.setOnClickListener(view -> {
if (wifiManager.isWifiEnabled()) {
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
wifiManager.setWifiEnabled(false);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
} else {
wifiManager.setWifiEnabled(true);
wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
}
});
wifi_descovery_iv.setOnClickListener(view -> p2pManager.discoverPeers(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText(R.string.discovery_on);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.purple_500));
}
#Override
public void onFailure(int i) {
connectionStatus.setText(R.string.discovery_off);
wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
connectionStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.red));
}
}));
p2pManager.createGroup(mchannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int i) {
}
});
listView.setOnItemClickListener((adapterView, view, i, l) -> {
final WifiP2pDevice device = wifiP2pDeviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
p2pManager.connect(mchannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected to " + device.deviceName, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int i) {
Toast.makeText(MainActivity.this, "Not connected", Toast.LENGTH_SHORT).show();
}
});
});
send_btn_iv.setOnClickListener(view -> {
// sendReceive = new SendReceive(sock);
messageText = Objects.requireNonNull(editText.getText()).toString().trim();
sendReceive.write(messageText.getBytes());
Toast.makeText(MainActivity.this, "you sent"+ messageText, Toast.LENGTH_SHORT).show();
});
}
private void initializeViews() {
intentFilter = new IntentFilter();
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
toolbar = findViewById(R.id.mdboard_toolbar);
wifi_on_off_iv = findViewById(R.id.md_wifi);
wifi_descovery_iv = findViewById(R.id.md_wifi_descov);
brd_msg_iv = findViewById(R.id.md_broadcast_mesaage);
editText = findViewById(R.id.md_editext);
sentMessage = findViewById(R.id.md_tally_message);
send_btn_iv = findViewById(R.id.md_send_btn);
save_ic_iv = findViewById(R.id.md_save);
username = findViewById(R.id.md_profile_username);
connectionStatus = findViewById(R.id.md_status_text);
listView = findViewById(R.id.md_list_view);
tallytext = findViewById(R.id.md_tally_text);
tallyno = findViewById(R.id.md_tally_no);
nestedLinearlayout = findViewById(R.id.nestedscroll_linearlayout);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.dashboard);
ViewCompat.setNestedScrollingEnabled(nestedLinearlayout, true);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
p2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mchannel = p2pManager.initialize(this, getMainLooper(), null);
broadcastReceiver = new WifiDirectBroadcastReceiver(p2pManager, mchannel, this);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
if (!wifiP2pDeviceList.getDeviceList().equals(peers)) {
peers.clear();
peers.addAll(wifiP2pDeviceList.getDeviceList());
devicenameArray = new String[wifiP2pDeviceList.getDeviceList().size()];
wifiP2pDeviceArray = new WifiP2pDevice[wifiP2pDeviceList.getDeviceList().size()];
int index = 0;
for (WifiP2pDevice device: wifiP2pDeviceList.getDeviceList()) {
devicenameArray[index] = device.deviceName;
wifiP2pDeviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, devicenameArray);
listView.setAdapter(adapter);
}
if (peers.size()==0) {
Toast.makeText(MainActivity.this, "No device found", Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener(){
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwner = wifiP2pInfo.groupOwnerAddress;
if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass = new ServerClass();
serverClass.start();
} else if (wifiP2pInfo.groupFormed){
connectionStatus.setText("CLient");
clientClass = new ClientClass(groupOwner);
clientClass.start();
}
}
};
#Override
protected void onStart(){
super.onStart();
exqListener();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
public class ServerClass extends Thread {
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt) {
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (socket!=null) {
try {
bytes = inputStream.read(buffer);
if (bytes>0){
handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
outputStream = new OutputStream() {
#Override
public void write(int i) throws IOException {
outputStream.write(bytes);
}
};
}
}
public class ClientClass extends Thread {
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// requestGroupInfo
private void requestGroupInfo() {
p2pManager.requestGroupInfo(mchannel, new WifiP2pManager.GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup wifiP2pGroup) {
connectionStatus.setText("request group info");
}
});
}
}
Here is my wifibroadcastReceiver class
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
WifiP2pManager wifiP2pManager;
WifiP2pManager.Channel channel;
MainActivity mainActivity;
public WifiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mchannel, MainActivity mActivity) {
this.wifiP2pManager = mManager;
this.channel = mchannel;
this.mainActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
mainActivity. wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_on);
Toast.makeText(context, "Wifi is on", Toast.LENGTH_SHORT).show();
} else {
mainActivity.wifi_on_off_iv.setImageResource(R.drawable.ic_wifi_off);
Toast.makeText(context, "Wifi is off", Toast.LENGTH_SHORT).show();
}
} else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// do somethimg
if (wifiP2pManager != null) {
wifiP2pManager.requestPeers(channel, mainActivity.peerListListener);
}
} else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// do somthing
if (wifiP2pManager == null) {
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
wifiP2pManager.requestConnectionInfo(channel, mainActivity.connectionInfoListener);
mainActivity.connectionStatus.setText("[Device connected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discover);
} else {
mainActivity.connectionStatus.setText("[Device disconnected]");
mainActivity.wifi_descovery_iv.setImageResource(R.drawable.ic_wifi_discovery_off);
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
I want to make a TCP client that can sent and receive data for server. I use Hercules(TCP/UDP test program) as Server. My code can send string "Submit" to Server. I try to make my code can receive data from Hercules but it not work.what I have to do for edit it?
This is my MainActivity code
public class MainActivity extends Activity {
// Used to reference UI elements of main.xml
private TextView text,serverResponse;
private EditText ipBox;
private EditText portBox;
private ToggleButton connect;
private Button send;
private static final String TAG = "CClient";
private String ipAddress;
private Socket client;
private DataOutputStream outToServer;
private DataInputStream inFromServer;
private boolean connected = false;
private final int START = 0xffffff;
private final int msgBoxHint = START;
private final int appendText = START + 1;
Toast mytoast , savetoast;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(TAG, "Here 1");
ipAddress = getLocalIpAddress();
Log.d(TAG, "Get local IP="+ ipAddress);
text = (TextView) findViewById(R.id.text);
ipBox = (EditText) findViewById(R.id.ipBox);
serverResponse = (TextView) findViewById(R.id.response);
portBox = (EditText) findViewById(R.id.portBox);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(buttonsendOnClickListener);
connect = (ToggleButton) findViewById(R.id.connect);
connect.setOnClickListener(buttonConnectOnClickListener);
Button buttonExit = (Button) findViewById(R.id.btnExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Exit");
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
}
finish();
}
});
}
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.connect:
if(connect.isChecked())
{
Log.d(TAG, "Connect" );
EditText edIP = (EditText) findViewById(R.id.ipBox);
String ed_textIP = edIP.getText().toString().trim();
if(ed_textIP.isEmpty() || ed_textIP.length() == 0 || ed_textIP.equals("") || ed_textIP == null )
{
Toast.makeText(MainActivity.this, "IP Address or PORT is incorrect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "IP Address or PORT is incorrect");
}
setValues(R.id.connect,true);
setValues(R.id.send,true);
setValues(R.id.ipBox,false);
String tMsg = welcomeMsg.toString();
MyClientTask myClientTask = new MyClientTask(ipBox
.getText().toString(), Integer.parseInt(portBox
.getText().toString()),
tMsg);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
myClientTask.execute();
}
else
{ /*Toast.makeText(this, ipBox.getText(), Toast.LENGTH_LONG).show();*/
Log.d(TAG, "Disconnect" );
if(client != null)
{
try {
client.close();
} catch (IOException e) {
Log.d(TAG, "Disconnect"+e.toString() );
}
setText(R.id.text,"Press the connect button to start the client");
setText(msgBoxHint,"");
setValues(R.id.connect,false);
setValues(R.id.ipBox,true);
setValues(R.id.send,false);
}
else
{
setValues(R.id.connect,false);
}
}
break;
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
String msgToServer;
MyClientTask(String addr, int port, String msgTo) {
dstAddress = addr;
dstPort = port;
msgToServer = msgTo;
}
protected Void doInBackground(Void... Arg0) {
Log.d(TAG, "InBackground");
Socket socket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
try {
client = new Socket(dstAddress, dstPort);
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream())); // Input stream <- from server
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.d(TAG, "InBackground 1");
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error UnknownHostException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
} catch (IOException e) {
Log.d(TAG, "InBackground 2");
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mytoast = Toast.makeText(MainActivity.this, "Error IOException",
Toast.LENGTH_SHORT);
mytoast.show();
setValues(R.id.connect,false);
setValues(R.id.send,false);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mytoast.cancel();
}
}, 500);
}
});
}finally {
Log.d(TAG, "InBackground 3");
if (socket != null) {
try {
socket.close();
Log.d(TAG, "InBackground 3.11");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "InBackground 3.12");
}
}
Log.d(TAG, "InBackground 3.1");
}
Log.d(TAG, "InBackground 4");
return null;
}
#Override
protected void onPostExecute(Void result) {
serverResponse.setText(response);
super.onPostExecute(result);
}
}
OnClickListener buttonsendOnClickListener = new OnClickListener() {
/** Manages all button clicks from the screen */
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.send:
Log.d(TAG, "Sent" );
String sentence = "Submit";
String recieve = "";
serverResponse = (TextView) findViewById(R.id.response);
try {
outToServer = new DataOutputStream(client.getOutputStream());
inFromServer = new DataInputStream(new BufferedInputStream(client.getInputStream()));
Log.d(TAG, "Sent 1-1" );
if(sentence != null){
outToServer.writeUTF(sentence);
outToServer.flush();
}
/*
*
*
*
*
*
*/
Log.d(TAG, "Sent 1-2"+ recieve);
} catch (IOException e) {
setValues(R.id.ipBox,true);
setValues(R.id.connect,false);
setValues(R.id.send,false);
}
break;
}
}
};
private String getLocalIpAddress() {
Log.d(TAG, "Here 2");
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Log.d(TAG, "Here 3");
WifiInfo info = wifi.getConnectionInfo();
Log.d(TAG, "Here 4");
return Formatter.formatIpAddress(info.getIpAddress());
}
private void setText(int view, String content)
{
switch(view)
{
case R.id.ipBox: ipBox.setText(content); break;
case R.id.text: text.setText(content+"\n\n"); break;
case appendText: text.append(content+"\n\n"); break;
}
}
private void setValues(int view, boolean value)
{
switch(view)
{
case R.id.ipBox: ipBox.setEnabled(value); break;
case R.id.send: send.setEnabled(value); break;
case R.id.connect: connect.setChecked(value); break;
}
}
}
I think, I have to add receive code in buttonsendOnClickListener near /*****/.
Do not work with sockets in main (gui) thread. Use AsyncTask!
Android fails if work with sockets in main (gui) thread.
Example:
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
// do in main thread before
}
#Override
protected Void doInBackground(Void... v) {
// do in thread, use sockets
return null;
}
#Override
protected void onPostExecute(Void v) {
super.onPostExecute(integer);
// do in main thread after
}
}.execute();
Learn about AsyncTask advance.
So, I want to create a TCP socket communication, client runs on Android. In the first Activity I create a Service, no problem. First activity correctly binds, works just fine. Next, I unBind from the Service, then I start the next Activity, when I try to bind to that Service, I get null from my localBinder. Code is below. If anyone has any idea, I'm all ears.
First Activity, works fine.
public class MainActivity extends Activity {
private EditText getIpAddressEditText;
private String IpAddress;
private Socket socket;
private boolean mIsBound;
private SocketService mService;
private EditText ipAddressEditText;
private Intent theIntent;
private ProgressDialog mDialog;
private BufferedWriter out;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theIntent = new Intent(MainActivity.this,SocketService.class);
getIpAddressEditText = (EditText) findViewById(R.id.get_ip_address_edit_text);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
public void OnConnectToServerButtonClick(View view) {
IpAddress = getIpAddressEditText.getText().toString();
theIntent.putExtra("IPADDRESS", IpAddress);
startService(theIntent);
doBindService();
new GetServerSocket().execute();
}
private void ConnectToServer() {
socket = mService.getSocket();
if (socket.isConnected()) {
SendMessageToServer("HELLO SERVER");
doUnbindService();
Intent intent = new Intent(MainActivity.this,GpsInterfaceActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_LONG).show();
doUnbindService();
stopService(theIntent);
}
}
public void OnGetIpFromSmsButtonClick(View view) {
}
private void doBindService() {
bindService(new Intent(MainActivity.this, SocketService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
public class GetServerSocket extends AsyncTask<Void, Void, String> {
public ProgressDialog progDailog;
public GetServerSocket() {}
private int a = 0;
#Override
public String doInBackground(Void... params) {
while ( a < 60) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a++;
if (mService != null) {
socket = mService.getSocket();
if (socket.isConnected()) {
break;
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
ConnectToServer();
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Second Activity:
public class GpsInterfaceActivity extends Activity {
private SocketService mService;
private Socket socket;
private BufferedWriter out;
private String[] list = new String[11];
private String DeviceId;
private String DeviceStatus;
private String DeviceTTFF;
private String DeviceNumberOfSatellites;
private String DeviceSpeed;
private String DeviceCourseOverGround;
private String DeviceAltitude;
private String DeviceLongitude;
private String DeviceLatitude;
private String DeviceNetworkStatus;
private String DeviceEnergykStatus;
private TextView ttffEditText;
private TextView satellitesEditText;
private TextView speedEditText;
private TextView courseOverGroundEditText;
private TextView networkStatusEditText;
private TextView deviceStatusEditText;
private TextView energyStatusEditText;
private ProgressBar energyProgressBar;
private boolean mIsBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_interface);
deviceStatusEditText = (TextView) findViewById(R.id.deviceStatusTextView);
ttffEditText = (TextView) findViewById(R.id.ttff_edit_text);
satellitesEditText = (TextView) findViewById(R.id.satellites_edit_text);
speedEditText = (TextView) findViewById(R.id.speed_edit_text);
courseOverGroundEditText = (TextView) findViewById(R.id.course_over_ground_edit_text);
networkStatusEditText = (TextView) findViewById(R.id.network_status_edit_text);
energyStatusEditText = (TextView) findViewById(R.id.energy_status_text_view);
energyProgressBar = (ProgressBar) findViewById(R.id.energy_proccess_bar);
doBindService();
if (mService != null) {
socket = mService.getSocket();
}else {
Toast.makeText(getApplicationContext(), "Connection Lost", Toast.LENGTH_LONG).show();
}
new IncomingData().execute();
SendMessageToServer("HELLO SERVER");
}
private ServiceConnection mConnectionn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
private void InputStreamTokenizer(String input) {
if (input.contains("DEVICE")) {
try {
list = input.split(";");
DeviceId = list[0];
DeviceStatus = list[1];
DeviceTTFF = list[2];
DeviceNumberOfSatellites = list[3];
DeviceSpeed = list[4];
DeviceCourseOverGround = list[5];
DeviceAltitude = list[6];
DeviceLongitude = list[7];
DeviceLatitude = list[8];
DeviceNetworkStatus = list[9];
DeviceEnergykStatus = list[10];
deviceStatusEditText.setText(DeviceStatus);
ttffEditText.setText(DeviceTTFF);
satellitesEditText.setText(DeviceNumberOfSatellites);
speedEditText.setText(DeviceSpeed);
courseOverGroundEditText.setText(DeviceCourseOverGround);
networkStatusEditText.setText(DeviceNetworkStatus);
energyStatusEditText.setText(DeviceEnergykStatus);
} catch (Exception e){}
}
}
public void SendMessageToServer(String string) {
try {
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write(string);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doBindService() {
bindService(new Intent(GpsInterfaceActivity.this, SocketService.class), mConnectionn, Context.BIND_ADJUST_WITH_ACTIVITY);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnectionn);
mIsBound = false;
}
}
public class IncomingData extends AsyncTask<Void, Void, String> {
public BufferedReader input;
public String read = null;
public int time = 0;
public IncomingData() {}
#Override
public String doInBackground(Void... params) {
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (input.ready()) {
read = input.readLine();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
}
return read;
}
#Override
public void onPostExecute(String input) {
if (input != null) {
InputStreamTokenizer(input);
}
new IncomingData().execute();
}
}
}
Service:
public class SocketService extends Service {
Socket s;
String IpAddress;
Intent intent;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return myBinder;
}
public Socket getSocket() {
return s;
}
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SocketService getService() {
return SocketService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
s = new Socket();
}
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
IpAddress = intent.getStringExtra("IPADDRESS");
new Thread(new SocketThread()).start();
}
public class SocketThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(IpAddress);
s = new Socket(serverAddr, 8080);
} catch (SocketException e1) {
e1.printStackTrace();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
Actually i am doing call using sip through wifi. bt in this program the problem is that I when i select sip account of the person whom i want to call but when i select the number and press ok then on then second phone there is no notification display that their is an inncoming call. Please help me I am stuck here ???
public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
public String sipAddress = null;
String DummyNum;
SipManager manager=null;
public SipProfile me = null;
public SipAudioCall call = null;
public IncomingCallReceiver callReceiver;
Button contact;
TextView tv;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.walkietalkie);
// PickContact();
contact = (Button) findViewById(R.id.button1);
contact.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
}
});
tv = (TextView) findViewById(R.id.textView1);
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);
// Set up the intent filter. This will be used to fire an
// IncomingCallReceiver when someone calls the SIP address used by this
// application.
IntentFilter filter = new IntentFilter();
filter.addAction("android.SipDemo.INCOMING_CALL");
callReceiver = new IncomingCallReceiver();
this.registerReceiver(callReceiver, filter);
// "Push to talk" can be a serious pain when the screen keeps turning off.
// Let's prevent that.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initializeManager();
}
#Override
public void onStart() {
super.onStart();
// When we get back from the preference setting Activity, assume
// settings have changed, and re-login with new auth info.
initializeManager();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.close();
}
closeLocalProfile();
if (callReceiver != null) {
this.unregisterReceiver(callReceiver);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeManager() {
if (manager == null) {
manager = SipManager.newInstance(this);
}
initializeLocalProfile();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initializeLocalProfile() {
if (manager == null) {
return;
}
if (me != null) {
closeLocalProfile();
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String username = prefs.getString("namePref", "");
String domain = prefs.getString("domainPref", "");
String password = prefs.getString("passPref", "");
if (username.length() == 0 || domain.length() == 0 || password.length() == 0) {
showDialog(UPDATE_SETTINGS_DIALOG);
return;
}
try {
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
me = builder.build();
Intent i = new Intent();
i.setAction("android.SipDemo.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
updateStatus("Registration failed. Please check settings.");
}
});
} catch (ParseException pe) {
updateStatus("Connection Error.");
} catch (SipException se) {
updateStatus("Connection error.");
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void initiateCall() {
updateStatus(sipAddress);
try {
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
// Much of the client's interaction with the SIP Stack will
// happen via listeners. Even making an outgoing call, don't
// forget to set up a listener to set things up once the call is established.
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
updateStatus(call);
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCallEnded(SipAudioCall call) {
updateStatus("Ready.");
}
};
call = manager.makeAudioCall(me.getUriString(), sipAddress, listener, 30);
} catch (Exception e) {
Log.i("WalkieTalkieActivity/InitiateCall", "Error when trying to close manager.", e);
if (me != null) {
try {
manager.close(me.getUriString());
} catch (Exception ee) {
Log.i("WalkieTalkieActivity/InitiateCall",
"Error when trying to close manager.", ee);
ee.printStackTrace();
}
}
if (call != null) {
call.close();
}
}
}
public void updateStatus(final String status) {
// Be a good citizen. Make sure UI changes fire on the UI thread.
this.runOnUiThread(new Runnable() {
public void run() {
TextView labelView = (TextView) findViewById(R.id.sipLabel);
labelView.setText(status);
}
});
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void updateStatus(SipAudioCall call) {
String useName = call.getPeerProfile().getDisplayName();
if (useName == null) {
useName = call.getPeerProfile().getUserName();
}
updateStatus(useName + "#" + call.getPeerProfile().getSipDomain());
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onTouch(View v, MotionEvent event) {
if (call == null) {
return false;
} else if (event.getAction() == MotionEvent.ACTION_DOWN && call != null && call.isMuted()) {
call.toggleMute();
} else if (event.getAction() == MotionEvent.ACTION_UP && !call.isMuted()) {
call.toggleMute();
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, CALL_ADDRESS, 0, "Call someone");
menu.add(0, SET_AUTH_INFO, 0, "Edit your SIP Info.");
menu.add(0, HANG_UP, 0, "End Current Call.");
return true;
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CALL_ADDRESS:
showDialog(CALL_ADDRESS);
break;
case SET_AUTH_INFO:
updatePreferences();
break;
case HANG_UP:
if (call != null) {
try {
call.endCall();
} catch (SipException se) {
Log.d("WalkieTalkieActivity/onOptionsItemSelected",
"Error ending call.", se);
}
call.close();
}
break;
}
return true;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CALL_ADDRESS:
LayoutInflater factory = LayoutInflater.from(this);
final View textBoxView = factory.inflate(R.layout.call_address_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Call Someone.")
.setView(textBoxView)
.setPositiveButton(
android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText textField = (EditText)
(textBoxView.findViewById(R.id.calladdress_edit));
DummyNum = textField.getText().toString();
tv.setText(DummyNum);
SendMessageWebTask webTask1 = new SendMessageWebTask(WalkieTalkieActivity.this);
webTask1.execute();
initiateCall();
}
}
)
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
case UPDATE_SETTINGS_DIALOG:
return new AlertDialog.Builder(this)
.setMessage("Please update your SIP Account Settings.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
updatePreferences();
}
})
.setNegativeButton(
android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Noop.
}
}
)
.create();
}
return null;
}
public void updatePreferences() {
Intent settingsActivity = new Intent(getBaseContext(),
SipSettings.class);
startActivity(settingsActivity);
}
public void PickContact() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE},
null, null, null
);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
// showSelectedNumber(type, number);
tv.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
}
public class SendMessageWebTask extends AsyncTask<String, Void, String> {
private static final String TAG = "WebTask";
private ProgressDialog progressDialog;
private Context context;
private String status;
public SendMessageWebTask(Context context) {
super();
this.context = context;
this.progressDialog = new ProgressDialog(context);
this.progressDialog.setCancelable(true);
this.progressDialog.setMessage("Checking User using Connecto...");
}
#Override
protected String doInBackground(String... params) {
status = invokeWebService();
return status;
}
#Override
protected void onPreExecute() {
Log.i(TAG, "Showing dialog...");
progressDialog.show();
}
#Override
protected void onPostExecute(String params) {
super.onPostExecute(params);
progressDialog.dismiss();
//params = USER_NOT_EXIST_CODE;
if (params.equals("008")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto", 7000);
toast.show();
MediaPlayer mp1 = MediaPlayer.create(WalkieTalkieActivity.this, R.raw.button_test);
mp1.start();
sipAddress = DummyNum;
performDial(DummyNum);
} else if (params.equals("001")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Requested user is not using Connecto... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else if (params.equals("100")) {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Server Error... Now Call is through GSM Network", 7000);
toast.show();
// sipAddress = DummyNum;
performDial(DummyNum);
// initiateCall();
} else {
Toast toast = Toast.makeText(WalkieTalkieActivity.this, "Your Call is Staring...", 7000);
toast.show();
sipAddress = DummyNum;
// performDial(DummyNum);
initiateCall();
}
// tv.setText(params);
}
private String invokeWebService() {
final String NAMESPACE = "http://tempuri.org/";
final String METHOD_NAME = Utility.verify_sip;
final String URL = Utility.webServiceUrl;
final String SOAP_ACTION = "http://tempuri.org/" + Utility.verify_sip;
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("phone", DummyNum);
Log.v("XXX", tv.getText().toString());
//request.addProperty("password", inputParam2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String status = result.toString();
Log.v("RESULT: ", status);
return status;
} catch (Exception e) {
Log.e("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
Log.i("------", "------");
}
return "EXCEPTION";
}
}
}
private void performDial(String numberString) {
if (!numberString.equals("")) {
Uri number = Uri.parse("tel:" + numberString);
Intent dial = new Intent(Intent.ACTION_CALL, number);
startActivity(dial);
}
}
}